Skip to content

alexjoffroy/laravel-localization

Repository files navigation

A Laravel package to handle localization from your routes

Latest Version on Packagist Software License Build Status Code Coverage Quality Score Total Downloads

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:

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, ...

Table of content

Installation

You can install the package via composer:

composer require alexjoffroy/laravel-localization

This package will automatically register itself.

Optionnaly, you can publish the config file config/localization.php:

php artisan vendor:publish --provider="AlexJoffroy\Localization\LocalizationServiceProvider --tag="config"

If you want to customize the default switch view:

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).

'default_locale' => config('app.fallback_locale'),

Supported locales

You can list all locales you want to support here.

Each key should be a locale code (en, fr, ...).

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.

'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.

# `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.

'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:

// 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

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email hello@alexjoffroy.me instead of using the issue tracker.

Credits

This package was originally build on top of the package skeleton provided by Spatie at spatie/skeleton-php

License

The MIT License (MIT). Please see License File for more information.