Easy localization for Laravel
Architecture note & recommended successor
This package generates routes dynamically per request, which has a number of side effects - most notably,
php artisan route:cacheisn't supported out of the box. For new projects or apps planning to migrate, niels-numbers/laravel-localizer is the recommended modern successor - same feature set, but with statically registered routes that supportroute:cachenatively. See the migration guide for the swap.This package remains actively maintained by @jordyvanderhaegen for users who need to stay on the current architecture. Compatibility updates (Laravel/PHP versions, security, small bug fixes) continue here.
Easy i18n localization for Laravel, an useful tool to combine with Laravel localization classes.
The package offers the following:
| Laravel | laravel-localization |
|---|---|
| 4.0.x | 0.13.x |
| 4.1.x | 0.13.x |
| 4.2.x | 0.15.x |
| 5.0.x/5.1.x | 1.0.x |
| 5.2.x-5.4.x (PHP 7 not required) | 1.2.x |
| 5.2.0-6.x (PHP version >= 7 required) | 1.4.x |
| 6.x-10.x (PHP version >= 7 required) | 1.8.x |
| 10.x-13.x (PHP version >= 8.2 required) | 2.0.x |
Install the package via composer: composer require mcamara/laravel-localization
For Laravel 5.4 and below it necessary to register the service provider.
In order to edit the default configuration you may execute:
php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"After that, config/laravellocalization.php will be created.
The configuration options are:
You may register the package middleware in the app/Http/Kernel.php file:
…If you are using Laravel 11, you may register in bootstrap/app.php file in closure withMiddleware:
…Add the following to your routes file:
// routes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function()
{
/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
Route::get('/', function()
{
return View::make('hello');
});
Route::get('test',function(){
return View::make('test');
});
});
/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/
Once this route group is added to the routes file, a user can access all locales added into supportedLocales (en and es by default).
For example, the above route file creates the following addresses:
// Set application language to English
http://url-to-laravel/en
http://url-to-laravel/en/test
// Set application language to Spanish
http://url-to-laravel/es
http://url-to-laravel/es/test
// Set application language to English or Spanish (depending on browsers default locales)
// if nothing found set to default locale
http://url-to-laravel
http://url-to-laravel/testThe package sets your application locale App::getLocale() according to your url. The locale may then be used for Laravel's localization features.
You may add middleware to your group like this:
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
], function(){ //...
});1.: It is strongly recommended to use a redirecting middleware.
Urls without locale should only be used to determine browser/default locale and to redirect to the localized url.
Otherwise, when search engine robots crawl for example http://url-to-laravel/test they may get different language content for each visit.
Also having multiple urls for the same content creates a SEO duplicate-content issue.
2.: It is strongly recommended to localize your links, even if you use a redirect middleware. Otherwise, you will cause at least one redirect each time a user clicks on a link. Also, any action url from a post form must be localized, to prevent that it gets redirected to a get request.
The following redirection middleware depends on the settings of hideDefaultLocaleInURL
and useAcceptLanguageHeader in config/laravellocalization.php:
Whenever a locale is present in the url, it will be stored in the session by this middleware.
If there is no locale present in the url, then this middleware will check the following
useAcceptLanguageHeader is set to true, compute locale from browser and redirect to url with locale.hideDefaultLocaleInURL is set to true.For example, if a user navigates to http://url-to-laravel/test and en is the current locale, it would redirect him automatically to http://url-to-laravel/en/test.
Similar to LocaleSessionRedirect, but it stores value in a cookie instead of a session.
Whenever a locale is present in the url, it will be stored in the cookie by this middleware.
In there is no locale present in the url, then this middleware will check the following
useAcceptLanguageHeader is set to true, compute locale from browser and redirect to url with locale.hideDefaultLocaleInURL is set to true.For example, if a user navigates to http://url-to-laravel/test and de is the current locale, it would redirect him automatically to http://url-to-laravel/de/test.
When the default locale is present in the url and hideDefaultLocaleInURL is set to true, then the middleware redirects to the url without locale.
For example, if es is the default locale, then http://url-to-laravel/es/test would be redirected to http://url-to-laravel/test and theApp::getLocale() would be
set to es.
This package comes with a bunch of helpers.
Localized URLS taken into account route model binding when generating the localized route,
aswell as the hideDefaultLocaleInURL and Translated Routes settings.
// If current locale is Spanish, it returns `/es/test`
<a href="{{ LaravelLocalization::localizeUrl('/test') }}">@lang('Follow this link')</a>Get current URL in specific locale:
// Returns current url with English locale.
{{ LaravelLocalization::getLocalizedURL('en') }}Returns a URL clean of any localization.
// Returns /about
{{ LaravelLocalization::getNonLocalizedURL('/es/about') }}Returns a route, localized to the desired locale. If the translation key does not exist in the locale given, this function will return false.
// Returns /es/acerca
{{ LaravelLocalization::getURLFromRouteNameTranslated('es', 'routes.about') }}Example of a localized link using routes with attributes
// An array of attributes can be provided.
// Returns /en/archive/ghosts, /fr/archive/fantômes, /pt/arquivo/fantasmas, etc.
<a href="{{ LaravelLocalization::getURLFromRouteNameTranslated( App::currentLocale(), 'routes.archive', array('category' => 'ghosts')) }}">Ghost Stories</a>Return all supported locales and their properties as an array.
{{ LaravelLocalization::getSupportedLocales() }}Return all supported locales but in the order specified in the configuration file. You can use this function to print locales in the language selector.
{{ LaravelLocalization::getLocalesOrder() }}Return an array with all the keys for the supported locales.
{{ LaravelLocalization::getSupportedLanguagesKeys() }}Return the key of the current locale.
{{ LaravelLocalization::getCurrentLocale() }}Return current locale's name as string (English/Spanish/Arabic/ ..etc).
{{ LaravelLocalization::getCurrentLocaleName() }}Return current locale's native name as string (English/Español/عربى/ ..etc).
{{ LaravelLocalization::getCurrentLocaleNative() }}Return current locale's regional name as string (en_GB/en_US/fr_FR/ ..etc).
{{ LaravelLocalization::getCurrentLocaleRegional() }}Return current locale's direction as string (ltr/rtl).
{{ LaravelLocalization::getCurrentLocaleDirection() }}Return the ISO 15924 code for the current locale script as a string; "Latn", "Cyrl", "Arab", etc.
{{ LaravelLocalization::getCurrentLocaleScript() }}Register the middleware LaravelLocalizationViewPath to set current locale as view-base-path.
Now you can wrap your views in language-based folders like the translation files.
resources/views/en/, resources/views/fr, ...
As you can modify the supportedLocales even by renaming their keys, it is possible to use the string uk instead of en-GB to provide custom lang url segments. Of course, you need to prevent any collisions with already existing keys and should stick to the convention as long as possible. But if you are using such a custom key, you have to store your mapping to the localesMapping array. This localesMapping is needed to enable the LanguageNegotiator to correctly assign the desired locales based on HTTP Accept Language Header. Here is a quick example how to map HTTP Accept Language Header 'en-GB' to url segment 'uk':
// config/laravellocalization.php
'localesMapping' => [
'en-GB' => 'uk'
],After that http://url-to-laravel/en-GB/a/b/c becomes ```ht
No open issues yet, or sync has not completed.