Introduction
This package is a simple localization package for Laravel. It includes a middleware to set the app locale to the language desired and a route to specify the language desired in a session variable.
Installation
composer require escuccim/translate
Then register the components in /config/app.php:
Add the following to the 'providers' array:
Escuccim\Translate\TranslateServiceProvider::class,
And register the middleware in /app/Http/Kernel.php in the $middlewareGroups array under 'web':
'web' => [
..
\Escuccim\Translate\Http\Middleware\SetLanguage::class,
],
In order for the middleware to work properly it should be listed after the StartSession middleware.
Publish the config files to /config/translate.php:
php artisan vendor:publish
Usage
The middleware will run on every web request and will perform the following, in order:
- If the subdomain corresponds to a language it will default the app locale to that language.
- If there is a session variable called 'locale' it will set the app locale to whatever is in the variable.
A route is also provided at /setlang/{lang} which will put whatever is in {lang} into the locale session variable.
Configuration
You should be specify most of what you need in the config file at /config/translate.php. It contains the following values:
- use_subdomain - a boolean which specifies whether you wish to set a default language based on the subdomain.
- languages - array which contains a list of languages as follows: '[lang]' => '[display]' where lang is the code for the language and display is the name to display in the drop-down menu. If you are not using the drop-down menu you can ignore this setting.
- subdomains - array containing the list of subdomains and languages as follows: '[subdomain]' => '[lang]' where lang is the code for the language. Note you do not need to include a key for a null subdomain, but you should include 'default' as a subdomain with the default language. 'default' is used if the subdomain doesn't match any subdomains specified.
- date_formats - array containing the languages used in your site along with the ISO 639 or RFC 1766 code for the locales. This is used to localize dates and times using strftime. Note that in order for this to work you must have the locales installed on your web server. Find more information on setlocale here and on strftime here.