Localizing A Laravel Web App
Following the series of Laravel posts, here is how to make a Laravel app adapt to whatever language the visitor has set as a preference on its browser, or how to show a default language in case your website does not support your visitor's language.
When localizing a website, I usually use the following process:
- Set the locale to the user's preferred language.
- Fallback to English when the user's preferred language is not supported by your site.
To achieve this, the first thing we need to do is add the following lines inside the App::before method, on the file app/filters.php:
// Set the locale of the app to the user's browser language
$browser_lang = substr(Request::server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
This will set the language to whatever first language the user browser has selected.
Then, set the fallback_locale variable inside the app/config/app.php to 'en', which will do for the falling back.
And that's it. Now just use the lang/ folder to add different language files in subfolders with their language code (i.e. lang/en/help.php for English, and lang/es/help.php for Spanish).
The strings inside the file should be wrapped in a PHP array, as follows:
'terms' => 'términos',
'help' => 'ayuda',
'items' => 'artículos',
Lastly, you can use anywhere in your Laravel app the strings inside the help.php file, just by writing trans('help.terms'), for instance—which is a shorthand for Lang::get('help.terms'). That code, will get the terms value corresponding to the user’s language, or to the fallback language if the user’s language does not exist.