Localization in Laravel 5

2015-03-15 Laravel

Creating multilingual project in Laravel isn’t as hard as it may look like. In this article I will show you how to apply basic localization feature.

For purposes of this article we will implement two languages. English language will be set as the main one and as a fallback language as well. Second one doesn’t really matter. It’s up to you which you will use. The point is to show the general idea how to deal with localization.

Preparation

In this example we will support both English and Polish. Open

/config/app.php

and after

'locale' => 'en',

create an array with all languages that you’re going to support in your project. I named this array as locales.

'locales' => [
  'en' => 'English',
  'pl' => 'Polish'
],

Then I altered users table in the database by adding new column that stores the key of mentioned array. It’s up to you how you will implement this part. My column is called lang and for every user it holds en or pl value that can be changed / updated anytime when user updates his profile by selecting proper language from a drop down.

The drop down is created in the controller and pulls data from the locales array. Next I pass this to the view that renders drop down using Laravel’s form helper.

private function getAvailableAppLangArray()
{
  $locales[''] = Lang::get('app.select_your_language');
 
  foreach (Config::get('app.locales') as $key => $value)
  {
    $locales[$key] = $value;
  }
 
  return $locales;
}

Config facade is responsible for pulling data from the configuration file.

Config::get('app.locales')

As you see, the first line is a simple placeholder that contains an empty value that tells user to pick one of the available options. You can simply ignore this line and replace it with array declaration like

$locales = array();

One again, this is very liberal implementation. You can deal with this using completely different approach. This is just a simple idea. OK. Let’s go further.

Now every time when user is logged in, we should check his lang value and store it as a session variable so it will be available between requests.

public function postLogin(Request $request)
{
  $credentials = $request->only('email', 'password');

  if ($this->auth->attempt($credentials, $request->has('remember')))
  {
    Session::put('lang', $this->auth->user()->lang);

    return redirect()->intended('/admin');
  }

  return redirect('/auth/login');
}

Above method has been explained briefly in my previous post about overriding Login and Registration functionality. In general I hope you get the idea. Just in a place where you authenticate user, pull his language value

$this->auth->user()->lang

and assign it into session variable (I called it lang as well, for consistency)

Session::put('lang', $this->auth->user()->lang);

Don’t forget to put

use Illuminate\Support\Facades\Session;

at the top of your file.

Setting the language

Now we’ll use middleware. What is a middleware? I won’t even try to reinvent the wheel and will suggest watching particular Laracasts lesson where Jeffrey Way explains it perfectly.

Create a file called SetApplicationLanguage.php and save it inside

/app/Http/Middleware/SetApplicationLanguage.php

Inside the file paste below code

<?php namespace App\Http\Middleware;

use App;
use Closure;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Config;

class SetApplicationLanguage {

  /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
  public function handle($request, Closure $next)
  {
    App::setLocale(Session::has('lang') ? Session::get('lang') : Config::get('app.locale'));

    return $next($request);
  }

}

Last thing is to call the middleware on every request.

Open

/app/Http/Kernel.php

and add new entry into below array

protected $middleware

Like

'App\Http\Middleware\SetApplicationLanguage',

This array holds the stack of middleware files that are called on every request.

Language itself

Finally prepare your language files under

/resources/lang/[YOUR_LANG_VARIABLE]

For example:

  • /resources/lang/en/app.php
  • /resources/lang/pl/app.php

Inside every app.php I have arrays with keys and values with translations

English app.php

'top_menu_your_profile' => 'Your profile',
'top_menu_logout' => 'Log Out',
'top_menu_logout_modal_content' => 'Are you sure, you want to log out :first_name?',
'top_menu_logout_modal_button_logout' => 'Log Out',
'top_menu_logout_modal_button_cancel' => 'Cancel',

Polish app.php

'top_menu_your_profile' => 'Twój profil',
'top_menu_logout' => 'Wyloguj',
'top_menu_logout_modal_content' => 'Czy jesteś pewny(a), że chcesz wylogować użytkownika :first_name?',
'top_menu_logout_modal_button_logout' => 'Wyloguj',
'top_menu_logout_modal_button_cancel' => 'Anuluj',

To learn how to use Localization, proceed to the official documentation.

I hope that this article helped you at least a little bit. Please leave a comment if you have any questions or concerns.