Yii2 Multilingual & Localization Support

Yii2 provides robust support for multilingual applications and localization, allowing you to translate UI content, dates, numbers, and messages into different languages. In this tutorial, we will cover both file-based translations and database-driven translations to make your application support multiple languages efficiently.


1. Understanding Yii2 Localization & Internationalization

Yii2 follows Internationalization (i18n) and Localization (L10n) principles:

  • Internationalization (i18n) – Making the application adaptable to different languages.
  • Localization (L10n) – Translating content, dates, numbers, and messages to match the user's locale.

Yii2 provides built-in tools for message translation, date formatting, and language switching.


2. Configuring Yii2 for Multilingual Support

First, enable multilingual support by defining supported languages in config/web.php:

'language' => 'en-US', // Default language
'sourceLanguage' => 'en-US', // Original language of messages
'components' => [
    'i18n' => [
        'translations' => [
            'app*' => [
                'class' => 'yii\i18n\PhpMessageSource', // File-based translations
                'basePath' => '@app/messages',
            ],
        ],
    ],
],

Here, we set:

  • language – The default language (en-US).
  • sourceLanguage – The language of untranslated messages.
  • i18n component – Handles message translation.

3. File-Based Translations in Yii2

3.1 Creating Message Files

Yii2 stores translations in PHP message files inside the messages/ directory.

For example, create a folder structure like this:

/messages
    /en
        app.php
    /fr
        app.php

Each file returns an array of translated strings.

Example: messages/en/app.php

return [
    'Hello' => 'Hello',
    'Welcome' => 'Welcome to our website',
    'Login' => 'Login',
];

Example: messages/fr/app.php

return [
    'Hello' => 'Bonjour',
    'Welcome' => 'Bienvenue sur notre site',
    'Login' => 'Connexion',
];

3.2 Using Translations in Views & Controllers

To display a translated message, use:

echo Yii::t('app', 'Hello'); 

If the user switches to French (fr), Yii2 will automatically load messages/fr/app.php, and the output will be:

Bonjour

If no translation is found, Yii2 will fallback to sourceLanguage.


4. Database-Driven Translations in Yii2

Instead of using message files, we can store translations in the database, making it easier to manage.

4.1 Create a Translation Table

Run the following migration:

php yii migrate/create create_translation_table

Then, define the table in migrations/m220101_000000_create_translation_table.php:

use yii\db\Migration;

class m220101_000000_create_translation_table extends Migration
{
    public function safeUp()
    {
        $this->createTable('{{%translation}}', [
            'id' => $this->primaryKey(),
            'category' => $this->string()->notNull(),
            'message' => $this->string()->notNull(),
            'language' => $this->string(10)->notNull(),
            'translation' => $this->text()->notNull(),
        ]);
    }

    public function safeDown()
    {
        $this->dropTable('{{%translation}}');
    }
}

Run the migration:

php yii migrate

4.2 Insert Translations into the Database

Insert some translations manually into the database:

INSERT INTO translation (category, message, language, translation) 
VALUES ('app', 'Hello', 'fr', 'Bonjour');

INSERT INTO translation (category, message, language, translation) 
VALUES ('app', 'Welcome', 'fr', 'Bienvenue sur notre site');

4.3 Implement Database Translation Component

Create a custom translation component in components/DbMessageSource.php:

namespace app\components;

use yii\i18n\MessageSource;
use Yii;

class DbMessageSource extends MessageSource
{
    protected function loadMessages($category, $language)
    {
        return Yii::$app->db->createCommand('SELECT message, translation FROM translation WHERE category=:category AND language=:language')
            ->bindValues([':category' => $category, ':language' => $language])
            ->queryAll(\PDO::FETCH_KEY_PAIR);
    }
}

4.4 Register the Component in config/web.php

'components' => [
    'i18n' => [
        'translations' => [
            'app*' => [
                'class' => 'app\components\DbMessageSource',
            ],
        ],
    ],
],

4.5 Using Database Translations in Views

Now, you can call translations in the same way:

echo Yii::t('app', 'Hello');

Yii2 will now fetch the translations from the database instead of files.


5. Switching Languages in Yii2

Allow users to switch languages dynamically by storing their preference in a session or cookie.

5.1 Create a Language Switcher in the Layout

<?= Html::a('English', ['site/change-language', 'lang' => 'en']) ?>
<?= Html::a('Français', ['site/change-language', 'lang' => 'fr']) ?>

5.2 Create the change-language Action in SiteController.php

public function actionChangeLanguage($lang)
{
    Yii::$app->session->set('language', $lang);
    Yii::$app->language = $lang;
    return $this->redirect(Yii::$app->request->referrer);
}

5.3 Apply the Language in config/bootstrap.php

Create a config/bootstrap.php file:

if (Yii::$app->session->has('language')) {
    Yii::$app->language = Yii::$app->session->get('language');
}

Register this file in config/web.php:

'bootstrap' => ['config/bootstrap.php'],

Now, the application will remember the user's selected language.


6. Formatting Dates & Numbers Based on Locale

Yii2 provides the Formatter component to format dates, numbers, and currencies according to the user's locale.

6.1 Enable Formatter in config/web.php

'components' => [
    'formatter' => [
        'class' => 'yii\i18n\Formatter',
        'defaultTimeZone' => 'Asia/Calcutta',
        'locale' => Yii::$app->language, // Use dynamic language
    ],
],

6.2 Format Dates, Numbers & Currencies in Views

echo Yii::$app->formatter->asDate('2024-01-01'); // 01 January 2024
echo Yii::$app->formatter->asCurrency(100, 'INR'); // ₹100.00
echo Yii::$app->formatter->asPercent(0.85); // 85%

Yii2 will automatically format based on the selected language.


Conclusion

Yii2 provides flexible multilingual and localization features.

  • File-based translations – Simple and fast for small apps
  • Database-driven translations – Scalable and ideal for large apps
  • Language switching – Store user preferences using session or cookies
  • Date & number formatting – Auto-formats based on the locale