Setup Multiple Languages For Your Web application Using Laravel Localization
Published: 2021-05-25 20:29:17

**Introduction**

Laravel Localization allows our application to adjust the language, cultural look and feel of a particular user to their needs. For example, a France-speaking user may choose to have the website presented in France language, whereas an English-speaking user may want to use English as the application language.

**Laravel Localization**

Laravel has a Localization feature built in. In this post, I will show you how we can use the Laravel Localization to create a multilingual website. In Laravel, there are different ways to use Localiz ation . You can make a middleware to handle the location based on the language selected by the user, or use localization based on the specific route.


> 
Step 1: Install Laravel update Version

By deafult, the local language of our framework is English, or en. When you have your project ready, go to *config/app.php* file and check this section.

  
    |--------------------------------------------------------------------------
    | Application Locale Configuration
    |-----------------------------------------------------------------------
    | The application locale determines the default locale that will be used
    | by the translation service provider. You are free to set this value
    | to any of the locales which will be supported by the application.
    
    'locale' => 'en',


> 
Step 2: Creating Translation Files

Now we’re going to create some folders with the locale name inside the resources / lang folder.
Now, create a file called sentence.php within all the four files, and add the following code.
For en account.php file


``` 
<?php

return array(   
     'title'    => 'Account',    
     'name'     => 'Name',    
     'email'    => 'E-mail',    
     'password' => 'Password',

);

``` 
For es account.php file,
``` 
<?php
return array(
    'title'    => 'Cuenta',
    'name'     => 'Nombre',
    'email'    => 'Correo electrónico',
    'password' => 'Contraseña',
);
``` 
For fr account.php file,
``` 
<?php
return array(
    'title'    => 'Paramètre de compte',
    'name'     => 'nom',
    'email'    => 'Courriel',
    'password' => 'passe',
);
``` 
You might put as many texts as you wish. I only took one piece of text for this demo. Now we’ve put all of the translations in place, let’s start working on the views, and let’s load our application above.


> 
Step 3: Setup the blade view.

Now  open your  resource / views app.blade.php file and place below code which is a markup just for a languages dropdown.


```
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light navbar-laravel">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data- 
                       toggle="collapse" data- 
                        target="#navbarSupportedContent" aria- 
                        controls="navbarSupportedContent" aria- 
                        expanded="false" aria-label="{{ __('Toggle 
                        navigation') }}">
                        <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" 
                    id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav mr-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ml-auto">
                        @php $locale = session()->get('locale'); @endphp
                        <li class="nav-item dropdown">
                            <a id="navbarDropdown" class="nav-link dropdown- 
                               toggle" href="#" role="button" data- 
                               toggle="dropdown" aria-haspopup="true" aria- 
                               expanded="false" v-pre>
                                Language <span class="caret"></span>
                            </a>
                            @switch($locale)
                                @case('fr')
                                <img src="{{asset('img/fr.png')}}" 
                                      width="30px" height="20x"> French
                                @break
                                @case('es')
                                <img src="{{asset('img/jp.png')}}" 
                                     width="30px" height="20x"> Spain
                                @break
                                @default
                                <img src="{{asset('img/us.png')}}" 
                                     width="30px" height="20x"> English
                            @endswitch
                            <div class="dropdown-menu dropdown-menu-right" 
                                 aria-labelledby="navbarDropdown">
                                <a class="dropdown-item" href="lang/en"><img 
                                   src="{{asset('img/us.png')}}" 
                                   width="30px" height="20x"> English</a>
                                <a class="dropdown-item" href="lang/fr"><img 
                                   src="{{asset('img/fr.png')}}" 
                                   width="30px" height="20x"> French</a>
                                <a class="dropdown-item" href="lang/es"><img 
                                   src="{{asset('img/es.png')}}" 
                                  width="30px" height="20x"> Spanish</a>
                      
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

``` 

> 
Step 4: Set up route, controller, and middleware

First, we’ll build a lang/{locale} route that we’ve just added to dropdown in our languages. Add the path below to and save your web.php routes file.


```
Route::get('lang/{locale}', 'LocalizationController@lang');
``` 
Next we must build a controller for managing our language change and middleware to dynamically alter the language of the program. Run commands to build a controller and middleware in terminal below.


```
php artisan make:controller LocalizationController

``` 

Now edit your controller for localization, and add lang() method as below.

```
<?php

// LocalizationController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App;

class LocalizationController extends Controller
{
    public function lang($locale)
    {
        App::setLocale($locale);
        session()->put('locale', $locale);
        return redirect()->back();
    }
}

```

Now, create a middleware using the following command.

```
php artisan make:middleware Localization
```
It will create a file inside the **app /Http /Middleware folder.**

Now open your new middleware file called **Localization.php** and update the handle method with below code. So, our final file looks like below.

```
<?php

// Localization.php

namespace App\Http\Middleware;

use Closure;
use App;

class Localization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}
```


> 
Step 5: Register the Localization Middleware

Now add the middleware in **App/Http/Kernel‘s $middlewareGroups** array like so:


```
protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\Localization::class,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
        ],
    ];
``` 
Finally, add the following code inside the resources **/views/ welcome.blade.php** file.


```
@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-body">
                <p>{{ __('account.title') }}</p>
                <p>{{ __('account.name') }}</p>
                <p>{{ __('account.email') }}</p>
                <p>{{ __('account.password') }}</p>
                  or  @lang('account.title')
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
``` 

We have successfully implemented Laravel Localization in this post, feel free to share your opinion in the comments box below.
If you would like to learn more about Laravel Localization, check the  [official documentation](https://laravel.com/docs/7.x/localization#introduction) .