tyler36/localization

Localization middleware

2.2 2021-09-21 06:04 UTC

This package is auto-updated.

Last update: 2024-05-21 11:45:59 UTC


README

This package is designed to simplify multi-locale applications. Simply add the required middleware and update your configuration.

Installation

  • Install package
composer require tyler36/localization
  • Publish configuration Run the command below to publish the configuration file
php artisan vendor:publish --provider=tyler36/localization

Middleware

Option 1: Header request

This middleware uses a request header to set the locale. By default, the query string is set to X-localization but can be changed through the config file. It's ideal for making request via javascript.

  • Register \Tyler36\Localization\Middleware\HeaderLocale::class

  • Set the header in via vanilla javascript or preferred javascript framework. For example, you can apply the header to all Axios request with the following:

// Set language to German ('de')
window.axios = axios;
window.axios.defaults.headers.common['X-localization'] = 'de';

Now, when you send a request to the endpoint Laravel will update the locale to match the setting, assuming it is configured as 'valid'.

Option 2: Query String

This middleware is designed to use a query string.

  • Register \Tyler36\Localization\Middleware\QueryStringLocale::class

  • Add the query string to a URL. By default, the query string is set to lang but can be changed through the config file.

    // This will return the site with default locale
    https://cool-site.dev

    // This will return the site with locale to to German (de)
    https://cool-site.dev?lang=de

Option 3: Member preference

This middleware uses an attribute on the User model to set the locale. When a member is logged in, it check their saved locale and applies it.

  • Register \Tyler36\Localization\Middleware\MemberLocale::class

  • Create the attribute on User models By default, the query string is set to locale but can be changed through the config file.

    $table->string('locale', 2)->default(app()->getLocale());

Option 4: Session

This middleware looks for a value in Laravel session.

  • Register \Tyler36\Localization\Middleware\SessionLocale::class

  • Create a route that saves the session_key => locale to the session By default, the session_key is set to locale but can be changed through the config file.

    $key = config('localization.session_key', 'locale');
    session([$key => request()->get($key)]);

or you could use the included controller by updating your route file

// routes/web.php
Route::get('/locale/{locale}', [
    'as' => 'localization.session',
    'uses' => '\Tyler36\Localization\Controller\LocaleController@session'
]);

// blade - create links
route('localization.session', [config('localization.session_key') => $locale]