A Laravel package to handle localization from your routes
, (*1)
This Laravel package gives you the ability to simply handle localization in your application. It provides a set of helpers so you can basically do stuff like:, (*2)
GET /en/about # Displays the about page in english
GET /fr/a-propos # Displays the about page in french
You can still continue to use Laravel core features such as testing, route caching, lang files, ..., (*3)
Table of content
Installation
You can install the package via composer:, (*4)
composer require alexjoffroy/laravel-localization
This package will automatically register itself., (*5)
Optionnaly, you can publish the config file config/localization.php
:, (*6)
php artisan vendor:publish --provider="AlexJoffroy\Localization\LocalizationServiceProvider --tag="config"
If you want to customize the default switch view:, (*7)
php artisan vendor:publish --provider="AlexJoffroy\Localization\LocalizationServiceProvider --tag="views"
Configuration
Default locale
The default locale can be changed in the config file. By default, this value is the same as the Laravel fallback_locale
(set in config/app.php
)., (*8)
'default_locale' => config('app.fallback_locale'),
Supported locales
You can list all locales you want to support here., (*9)
Each key should be a locale code (en, fr, ...)., (*10)
The native
field is the label which will be rendered in the switch view.
regional_code
, charset
, and constants
fields are required to work with PHP's setlocale, which is called in Localization::setLocale
. This is useful for stuff like date formatting with Carbon., (*11)
'supported_locales' => [
'en' => [
'native' => 'English',
'regional_code' => 'en_GB',
'charset' => 'UTF-8',
'constants' => ['LC_TIME'],
],
'fr' => [
'native' => 'Français',
'regional_code' => 'fr_FR',
'charset' => 'UTF-8',
'constants' => ['LC_TIME'],
],
],
Hide default locale in url
By default, all URLs will be prefixed with the locale., (*12)
# `en` is default locale
GET /en/about # Displays the about page in english
GET /fr/a-propos # Displays the about page in french
When setting hide_default_locale_in_url
to true, this prefix will be removed for the default locale., (*13)
'hide_default_locale_in_url' => false,
# `en` is default locale
GET /about # Displays the about page in english
GET /fr/a-propos # Displays the about page in french
## Usage
### Register the middleware
The first step is to register the `SetLocaleFromCurrentRoute` middleware into your app. This middleware will guess and set the current locale from the URL.
The easiest way to do that is to register it globally:
```php
// app/Http/Kernel.php
protected $middleware = [
// ...
\AlexJoffroy\Localization\Http\Middlewares\SetLocaleFromCurrentRoute::class,
];
### Add your routes
You are now able to register your locales routes, with a convenient helper:
// routes/web.php
Route::locales(function() {
Route::get(
trans('routes.about'),
'App\Http\Controllers\AboutController@index'
)->name('about');
});
**_Warning: all routes defined inside the `locales` group should be named._**
According you are supporting `en` and `fr` locales and you defined translations for `routes.about`, the above code will register these routes:
| Verb | URL | Name | Action |
| ------------ |------------ | -------- | ------------------------------------------ |
| GET HEAD | en/about | en.about | App\Http\Controllers\AboutController@index |
| GET HEAD | fr/a-propos | fr.about | App\Http\Controllers\AboutController@index |
### The Localization instance
The `\AlexJoffroy\Localization\Localization` class provides a set of methods which could be helpful to use in your app. The object is registered as a singleton and can be accessed from the app container, the `L10n` facade or the `l10n()` helper.
$l10n = app('localization');
// or
$l10n = L10n::getFacadeRoot();
// or
$l10n = l10n();
#### Get/Set locale
// Given `en` is the current locale
$l10n->getLocale(); // `en`
$l10n->setLocale('fr'); // Set the current locale to `fr`
_`Localization::getLocale` and `Localization::setLocale` are aliases for `App::getLocale` and `App::setLocale`_
#### Checks
// Given `en` is the current locale
$l10n->isCurrentLocale('en'); // true
$l10n->isCurrentLocale('not-current'); // false
$l10n->isSupportedLocale('en'); // true
$l10n->isSupportedLocale('not-supported'); // false
// Given `en` is the default locale
$l10n->isDefaultLocale('en'); // true
$l10n->isDefaultLocale('not-default'); // false
#### Get config values
$l10n->getSupportedLocales(); // All supported locales (from supported_locales)
$l10n->getSupportedLocale('en'); // Given supported locale (from supported_locales)
$l10n->getSupportedLocaleKeys(); // All supported locale keys (from supported_locales)
$l10n->getDefaultLocale(); // Default locale (from default_locale)
// Given `en` is the default locale
$l10n->shouldHideLocaleInUrl('en'); // True if `hide_default_locale_in_url` is true
$l10n->shouldHideLocaleInUrl('fr'); // False, even if `hide_default_locale_in_url` is true
#### Generate routes
$l10n->route('about', [], true, 'en'); // `https://yourapp.com/en/about`
$l10n->route('about', [], false, 'en'); // `/en/about`
$l10n->route('about', [], true, 'fr'); // `https://yourapp.com/fr/a-propos`
// Shortcut will fallback to current locale
$l10n->route('about'); // `https://yourapp.com/en/about`
// Given the current app url is `https://yourapp.com/en/about`
$l10n->currentRoute('fr'); // `https://yourapp.com/fr/a-propos`
$l10n->currentRoute('fr', false); // `/fr/a-propos`
#### Render switch
This should be called in a Blade view like `{{ l10n()->renderSwitch() }}`. When using a custom view, you can directly access the Localization instance from `$l10n` variable.
// Default view
$l10n->renderSwitch();
// Custom view
$l10n->renderSwitch('path.to.view');
// Custom view, with additional data
$l10n->renderSwitch('path.to.view', ['foo' => 'bar']);
Custom view example:
<select name="switch" id="switch">
@foreach($l10n->getSupportedLocales() as $locale => $localeSettings)
<option value="{{ $locale }}" {{ $l10n->isCurrentLocale($locale) ? 'selected' : '' }}>
{{ ucfirst($localeSettings['native']) }}
</option>
@endforeach
</select>
#### Facade
The Localization methods are also available from the `L10n` facade.
L10n::getLocale();
L10n::setLocale();
L10n::route();
L10n::currentRoute();
// etc
#### Helpers
// Get the Localization instance
$l10n = l10n();
// Get the current locale
$current = locale();
// Set the current locale
locale('en');
// Get supported locale
$supported = locales();
## Testing
``` bash
composer test
Changelog
Please see CHANGELOG for more information what has changed recently., (*14)
Contributing
Please see CONTRIBUTING for details., (*15)
Security
If you discover any security related issues, please email hello@alexjoffroy.me instead of using the issue tracker., (*16)
Credits
This package was originally build on top of the package skeleton provided by Spatie at spatie/skeleton-php, (*17)
License
The MIT License (MIT). Please see License File for more information., (*18)