Laravel – Localization

To localize a Laravel application, it’s need to provide multiple language files. After that, Laravel can use the provided tools to localize applications in multiple languages based on user language. With that set of tools, introducing a new language in your application is as simple as providing new translation files. Currently, Laravel supports two formats of translation files. The first option is .php file, which can be interpreted as a text file. The second option is .json file, which is more complex but still a very popular file format and should be compatible with various tools.

Parameters in strings

In phrases, we can use variables that can be later replaced by user-specific values. This is useful when we wish to personalize messages. For example we can reference users by their provided names. This variable’s system is used in Laravel validation. Each error message provides information about the field that has invalid data. Additionally, we can customize these validation error messages.

Laravel provides validation error messages in a single file. Translation of this file should not be missed. It grants consistency and readable errors, whatever the language the user is currently using.

// /app/lang/en/messages.php
<?php


return [
   'welcome' => 'Hello :name'
];
// Print: "Hello John Smith"
echo __('messages.welcome', ['name' => 'John Smith']);

Pluralization

Laravel Localization provides a solution to the pluralization of phrases. Laravel can’t adjust phrases on its own. But if translations provide different phrases based on numeric range, then Laravel can choose which phrase should be used in this scenario.

// /app/lang/en/messages.php
<?php


return [
   'items' => '{0} There is zero items in your cart|{1} There is one item in your cart|[2,*] There are multiple items in your cart',
];
// Print: "There is zero items in your cart"
echo trans_choice('messages.items', 0);


// Print: "There is one item in your cart"
echo trans_choice('messages.items', 1);


// Print: "There are multiple items in your cart"
echo trans_choice('messages.items', 5);