mcamara / laravel-localization by mcamara

Easy localization for Laravel
5,992,572
3,295
96
Package Data
Maintainer Username: mcamara
Maintainer Contact: mcamara88@gmail.com (Marc Cámara)
Package Create Date: 2013-08-25
Package Last Update: 2024-03-17
Home Page:
Language: PHP
License: MIT
Last Refreshed: 2024-04-15 15:09:13
Package Statistics
Total Downloads: 5,992,572
Monthly Downloads: 96,744
Daily Downloads: 1,783
Total Stars: 3,295
Total Watchers: 96
Total Forks: 504
Total Open Issues: 80

Laravel Localization

Join the chat at https://gitter.im/mcamara/laravel-localization

Latest Stable Version Total Downloads Build Status Open Source Helpers Reviewed by Hound

Easy i18n localization for Laravel, an useful tool to combine with Laravel localization classes.

Table of Contents

  • Installation
    • Composer
    • Manually
    • Laravel
  • Config
    • Config files
    • Service providers
  • Usage
    • Middleware
  • Helpers
    • Route Model Binding
  • Translated Routes
  • Caching routes
  • Changelog
  • License

Laravel compatibility

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.x-5.8.x (PHP 7 required) | 1.3.x

Installation

Install the package via composer: composer require mcamara/laravel-localization

In Laravel 5.5, the service provider and facade will automatically get registered. For older versions of the framework, follow the steps below:

Register the service provider in config/app.php

        'providers' => [
		// [...]
                Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider::class,
        ],

You may also register the LaravelLocalization facade:

        'aliases' => [
		// [...]
                'LaravelLocalization' => Mcamara\LaravelLocalization\Facades\LaravelLocalization::class,
        ],

Config

Config Files

In order to edit the default configuration (where for e.g. you can find supportedLocales) for this package you may execute:

php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"

After that, config/laravellocalization.php will be created. Inside this file you will find all the fields that can be edited in this package.

Service Providers

Otherwise, you can use ConfigServiceProviders (check this file for more info).

For example, editing the default config service provider that Laravel loads when it's installed. This file is placed in app/providers/ConfigServicePovider.php and would look like this:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ConfigServiceProvider extends ServiceProvider {
	public function register()
	{
		config([
			'laravellocalization.supportedLocales' => [
				'ace' => array( 'name' => 'Achinese', 'script' => 'Latn', 'native' => 'Aceh' ),
				'ca'  => array( 'name' => 'Catalan', 'script' => 'Latn', 'native' => 'català' ),
				'en'  => array( 'name' => 'English', 'script' => 'Latn', 'native' => 'English' ),
			],

			'laravellocalization.useAcceptLanguageHeader' => true,

			'laravellocalization.hideDefaultLocaleInURL' => true
		]);
	}

}

This config would add Catalan and Achinese as languages and override any other previous supported locales and all the other options in the package.

You can create your own config providers and add them on your application config file (check the providers array in config/app.php).

Usage

Laravel Localization uses the URL given for the request. In order to achieve this purpose, a route group should be added into the routes.php file. It will filter all pages that must be localized.

// app/Http/routes.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, look at the config section to change that option). For example, a user can now access two different locales, using the following addresses:

http://url-to-laravel/en
http://url-to-laravel/es
http://url-to-laravel

If the locale is not present in the url or it is not defined in supportedLocales, the system will use the application default locale or the user's browser default locale (if defined in config file).

Once the locale is defined, the locale variable will be stored in a session (if the middleware is enabled), so it is not necessary to write the /lang/ section in the url after defining it once, using the last known locale for the user. If the user accesses to a different locale this session value would be changed, translating any other page he visits with the last chosen locale.

Template files and all locale files should follow the Lang class.

Middleware

Moreover, this package includes a middleware object to redirect all "non-localized" routes to the corresponding "localized".

So, if a user navigates to http://url-to-laravel/test and the system has this middleware active and 'en' as the current locale for this user, it would redirect (302) him automatically to http://url-to-laravel/en/test. This is mainly used to avoid duplicate content and improve SEO performance.

To do so, you have to register the middleware in the app/Http/Kernel.php file like this:

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {
	/**
	 * The application's route middleware.
	 *
	 * @var array
	 */
	protected $routeMiddleware = [
		/**** OTHER MIDDLEWARE ****/
		'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
		'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
		'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
                'localeViewPath' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class
		// REDIRECTION MIDDLEWARE
	];
}
// app/Http/routes.php

Route::group(
[
	'prefix' => LaravelLocalization::setLocale(),
	'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
],
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 **/

In order to activate it, you just have to attach this middleware to the routes you want to be accessible localized.

If you want to hide the default locale but always show other locales in the url, switch the hideDefaultLocaleInURL config value to true. Once it's true, if the default locale is en (english) all URLs containing /en/ would be redirected to the same url without this fragment '/' but maintaining the locale as en (English).

When hideDefaultLocaleInURL and useAcceptLanguageHeader are both set to true,then the language negotiation using the Accept-Language header will only occur while the session('locale') is empty. After negotiation, the session('locale') will be set accordingly and will not be called again.

Set current locale as view-base-path

To set the current locale as view-base-path, simply register the localeViewPath-middlware in your Kernel.php, like it is descriped above.

Now you can wrap your views in language-based folders like the translation files.

resources/views/en/, resources/views/fr, ...

Map your own custom lang url segments

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'
],

Helpers

This package comes with some useful functions, like:

Get URL for an specific locale

/**
 * Returns an URL adapted to $locale
 *
 * @param  string|boolean 	$locale	   	Locale to adapt, false to remove locale
 * @param  string|false		$url		URL to adapt in the current language. If not passed, the current url would be taken.
 * @param  array 		$attributes	Attributes to add to the route, if empty, the system would try to extract them from the url.
 *
 * @throws UnsupportedLocaleException
 *
 * @return string|false				URL translated, False if url does not exist
 */
public function getLocalizedURL($locale = null, $url = null, $attributes = array())

//Should be called in a view like this:
{{ LaravelLocalization::getLocalizedURL(optional string $locale, optional string $url, optional array $attributes) }}

It returns a URL localized to the desired locale.

Route Model Binding

Note that route model binding is taken into account when generating the localized route.

Get Clean routes

/**
 * It returns an URL without locale (if it has it)
 * Convenience function wrapping getLocalizedURL(false)
 *
 * @param  string|false 	$url	  URL to clean, if false, current url would be taken
 *
 * @return stringURL 			  with no locale in path
 */
public function getNonLocalizedURL($url = null)

//Should be called in a view like this:
{{ LaravelLocalization::getNonLocalizedURL(optional string $url) }}

It returns a URL clean of any localization.

Get URL for an specific translation key

/**
 * Returns an URL adapted to the route name and the locale given
 *
 * @throws UnsupportedLocaleException
 *
 * @param  string|boolean 		$locale 		Locale to adapt
 * @param  string 			$transKeyName  		Translation key name of the url to adapt
 * @param  array 			$attributes  		Attributes for the route (only needed if transKeyName needs them)
 *
 * @return string|false 					URL translated
 */
public function getURLFromRouteNameTranslated($locale, $transKeyName, $attributes = array())

//Should be called in a view like this:
{{ LaravelLocalization::getURLFromRouteNameTranslated(string $locale, optional array $transKeyNames, optional array $attributes) }}

It returns a route, localized to the desired locale using the locale passed. If the translation key does not exist in the locale given, this function will return false.

Get Supported Locales

/**
 * Return an array of all supported Locales
 *
 * @return array
 */
public function getSupportedLocales()

//Should be called like this:
{{ LaravelLocalization::getSupportedLocales() }}

This function will return all supported locales and their properties as an array.

Get Supported Locales Custom Order

/**
 * Return an array of all supported Locales but in the order the user
 * has specified in the config file. Useful for the language selector.
 *
 * @return array
 */
public function getLocalesOrder()

//Should be called like this:
{{ LaravelLocalization::getLocalesOrder() }}

This function will 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.

Get Supported Locales Keys

/**
 * Returns supported languages language key
 *
 * @return array 	keys of supported languages
 */
public function getSupportedLanguagesKeys()

//Should be called like this:
{{ LaravelLocalization::getSupportedLanguagesKeys() }}

This function will return an array with all the keys for the supported locales.

Set Locale

/**
 * Set and return current locale
 *
 * @param  string $locale	        Locale to set the App to (optional)
 *
 * @return string 			Returns locale (if route has any) or null (if route does not have a locale)
 */
public function setLocale($locale = null)

//Should be called in a view like this:
{{ LaravelLocalization::setLocale(optional string $locale) }}

This function will change the application's current locale. If the locale is not passed, the locale will be determined via a cookie (if stored previously), the session (if stored previously), browser Accept-Language header or the default application locale (depending on your config file).

The function has to be called in the prefix of any route that should be translated (see Filters sections for further information).

Get Current Locale

/**
 * Returns current language
 *
 * @return string current language
 */
public function getCurrentLocale()

//Should be called in a view like this:
{{ LaravelLocalization::getCurrentLocale() }}

This function will return the key of the current locale.

Get Current Locale Name

/**
 * Returns current locale name
 *
 * @return string current locale name
 */
public function getCurrentLocaleName()

//Should be called in a view like this:
{{ LaravelLocalization::getCurrentLocaleName() }}

This function will return current locale's name as string (English/Spanish/Arabic/ ..etc).

Get Current Locale Direction

/**
 * Returns current locale direction
 *
 * @return string current locale direction
 */
public function getCurrentLocaleDirection()

//Should be called in a view like this:
{{ LaravelLocalization::getCurrentLocaleDirection() }}

This function will return current locale's direction as string (ltr/rtl).

Get Current Locale Script

/**
 * Returns current locale script
 *
 * @return string current locale script
 */
public function getCurrentLocaleScript()

//Should be called in a view like this:
{{ LaravelLocalization::getCurrentLocaleScript() }}

This function will return the ISO 15924 code for the current locale script as a string; "Latn", "Cyrl", "Arab", etc.

Creating a language selector

If you're supporting multiple locales in your project you will probably want to provide the users with a way to change language. Below is a simple example of blade template code you can use to create your own language selector.

<ul>
    @foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
        <li>
            <a rel="alternate" hreflang="{{ $localeCode }}" href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
                {{ $properties['native'] }}
            </a>
        </li>
    @endforeach
</ul>

Here default language will be forced in getLocalizedURL() to be present in the URL even hideDefaultLocaleInURL = true.

Note that Route Model Binding is supported.

Translated Routes

You can adapt your URLs depending on the language you want to show them. For example, http://url/en/about and http://url/es/acerca (acerca is about in spanish) or http://url/en/view/5 and http://url/es/ver/5 (view == ver in spanish) would be redirected to the same controller using the proper filter and setting up the translation files as follows:

As it is a middleware, first you have to register in on your app/Http/Kernel.php file like this:

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {
	/**
	 * The application's route middleware.
	 *
	 * @var array
	 */
	protected $routeMiddleware = [
		/**** OTHER MIDDLEWARE ****/
		'localize' => 'Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes',
		// TRANSLATE ROUTES MIDDLEWARE
	];
}
// app/Http/routes.php

Route::group(
[
	'prefix' => LaravelLocalization::setLocale(),
	'middleware' => [ 'localize' ] // Route translate middleware
],
function() {
	/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
	Route::get('/', function() {
		// This routes is useless to translate
		return View::make('hello');
	});

	Route::get(LaravelLocalization::transRoute('routes.about'), function() {
		return View::make('about');
	});

	Route::get(LaravelLocalization::transRoute('routes.view'), function($id) {
		return View::make('view',['id'=>$id]);
	});
});

/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/

In the routes file you just have to add the LaravelLocalizationRoutes filter and the LaravelLocalization::transRoute function to every route you want to translate using the translation key.

Then you have to create the translation files and add there every key you want to translate. I suggest to create a routes.php file inside your resources/lang/language_abbreviation folder. For the previous example, I have created two translations files, these two files would look like:

// resources/lang/en/routes.php
return [
	"about" 	=> 	"about",
	"view" 		=> 	"view/{id}", //we add a route parameter
	// other translated routes
];
// resources/lang/es/routes.php
return [
	"about" 	=> 	"acerca",
	"view" 		=> 	"ver/{id}", //we add a route parameter
	// other translated routes
];

Once files are saved, you can access to http://url/en/about , http://url/es/acerca , http://url/en/view/5 and http://url/es/ver/5 without any problem.

Events

You can capture the URL parameters during translation if you wish to translate them too. To do so, just create an event listener for the routes.translation event like so:

Event::listen('routes.translation', function($locale, $attributes)
{
	// Do your magic

	return $attributes;
});

Be sure to pass the locale and the attributes as parameters to the closure. You may also use Event Subscribers, see: http://laravel.com/docs/events#event-subscribers

Caching routes

More information on support on cached (translated) routes here.

Note that the separate czim/laravel-localization-route-cache package is no longer required.

Changelog

View changelog here -> changelog

License

Laravel Localization is an open-sourced laravel package licensed under the MIT license