CodeIgniter 4 Multi Language Website

Introduction

In this tutorial I am going to show you an example on CodeIgniter 4 multi language website. So the website built on CodeIgniter multilingual or multi-languages will have representations of the same information in different languages. I am going to use three different languages en (English), hi (Hindi), fr (French). You can have more language to make your website internationalization (i18n).

CodeIgniter provides several tools to help you localize your application for different languages. While full localization of an application is a complex subject, it’s simple to swap out strings in your application with different supported languages.

Related Posts:

Language strings are stored in the app/Language directory, with a sub-directory for each supported language:

codeigniter 4 multi language website

Prerequisites

PHP 7.4.3, Codeigniter 4.0.4/4.1.4

Project Directory

It’s assumed that you have already setup PHP and CodeIgniter in Windows system. Now I will create a project root directory called codeigniter-multi-language-website anywhere in the system.

Now move all the directories and files from CodeIgniter framework into the project root directory.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

Locale Configuration

Every site will have a default language/locale they operate in. This can be set in app/Config/App.php. By default it is set to en (English) language/locale.

public $defaultLocale = 'en';

The system is smart enough to fall back to more generic language codes if an exact match cannot be found. If the locale code was set to en-US and we only have language files set up for en then those will be used since nothing exists for the more specific en-US. If, however, a language directory existed at app/Language/en-US then that would be used first.

Locale Detection

There are two methods supported to detect the correct locale during the request. The first is a “set and forget” method that will automatically perform content negotiation for you to determine the correct locale to use. The second method allows you to specify a segment in your routes that will be used to set the locale.

Content Negotiation

You can set up content negotiation to happen automatically by setting two additional settings in Config/App. The first value tells the Request class that you do want to negotiate a locale, so simply set it to true:

public $negotiateLocale = true;

Once this is enabled, the system will automatically negotiate the correct language based upon an array of locales that you have defined in $supportLocales. If no match is found between the languages that you support, and the requested language, the first item in $supportedLocales will be used. In the following example, the en locale would be used if no match is found:

public $supportedLocales = ['en', 'es', 'fr-FR'];

For this example I have set the following supported languages:

public $supportedLocales = ['hi', 'en', 'fr'];

In Routes

The second method uses a custom placeholder to detect the desired locale and set it on the Request. The placeholder {locale} can be placed as a segment in your route. If present, the contents of the matching segment will be your locale:

$routes->get('{locale}/books', 'App\Books::index');

In this example, if the user tried to visit http://example.com/fr/books, then the locale would be set to fr, assuming it was configured as a valid locale.

For this example, I have configured the route as given below, I am using the controller file Home.php:

$routes->get('/{locale}', 'Home::index');

Current Locale

The current locale can always be retrieved from the incoming request object, through the getLocale() method. If your controller is extending CodeIgniter\Controller, this will be available through $this->request:

<?php

namespace App\Controllers;

class UserController extends \CodeIgniter\Controller {

    public function index() {
        $locale = $this->request->getLocale();
    }
	
}

Alternatively, you can use the Services class to retrieve the current request:

$locale = service('request')->getLocale();

Localization Implementation

Languages do not have any specific naming convention that are required. The file should be named logically to describe the type of content it holds. Here I am going to create app.php file for each of three different languages.

Within the file, you would return an array, where each element in the array has a language key and can have string to return:

'language_key' => 'The actual message to be shown.'

It also support nested definition:

'language_key' => [
    'nested' => [
        'key' => 'The actual message to be shown.'
    ],
],

I have created the following app.php file under app/Langugae/en folder with the following content:

<?php

return [
	'msg' => 'Internationalization Example in Codeigniter 4',
	'welcome' => 'Welcome to English Language',
	'copyright' => 'Copyright',
	'year' => '2021'
];

Similarly I have created for Hindi and French also under app/Langugae/hi and app/Langugae/fr folders respectively. Later you can download the whole source code from the Source Code section.

View File

The view file which is going to display the content has the following code:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title><?php echo lang('app.msg'); ?> - CodeIgniter 4 Multi Language Website</title>
	<meta name="description" content="The small framework with powerful features">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>
</head>
<body>
	<div id="container">
	<h1><?php echo lang('app.msg'); ?></h1>

	<div id="body">
		<div style="clear: both"></div>
		<div>
			<?php echo lang('app.copyright'); ?> © <?php echo lang('app.year'); ?>
		</div>
	</div>
</body>
</html>

The lang() method is used to display the value in different languages for the given key, for example, app.msg, app.copyright, where app is the name of the PHP file name.

Testing the Application

I am not going to use any external server but CLI command to run the application. Make sure you start the MySQL database server before you start your application. If you want to use external server to run your application you can use. Execute the following command on your project root directory to run your application.

php spark serve

Your application will be running on localhost and port 8080.

The URL http://localhost:8080/ will show you the following page on the browser. The default language it fall backs to en as set in the app/Config/App.php file.

codeigniter 4 multi language website

For Hindi you can type http://localhost:8080/hi/:

codeigniter 4 multi language website

For French, you can type http://localhost:8080/fr/:

codeigniter 4 multi language website

Hope you got an idea how to build multi language website in CodeIgniter 4 framework.

Source Code

Download

Author: Soumitra

Hi, I am, Soumitra, the owner of roytuts.com and it is my passion for sharing my knowledge and I have been writing blogs on various technologies since 2014. If you like my tutorials, you may also want to like my Facebook Page, follow me on Twitter, Github.

Leave a Reply

Your email address will not be published. Required fields are marked *