How to use Laravel Localization?

Laravel Localization is a switch language feature, supported by Laravel applications. Therefore, it allows a user to switch entire application language to a new and different language, as defined in the locales.

This tutorial explains the use of Laravel Localization ‘the language switch’ feature of Laravel applications.

Step 1: Create new lang files: Laravel Localization

Language files are created under the resources directory. As follows:

resources/lang/en/welcome.php

Each language folder is in a separate directory. It has separate files, where the arrays return messages in the specific language.

Suppose we add two languages to our application. i.e. English and French. We create two language files as follows.

resources/lang/en/welcome.php

<?php
  
return [
    'welcome_message' => 'Welcome to Scratch Coding.',
];

resources/lang/fr/welcome.php

<?php
  
return [
    'welcome_message' => 'Bienvenue dans Scratch Coding.',
];

The above two code snippets show how we can add a single message in English and French, and use that array throughout our Laravel application.

Step 2: Create Routes for Lang Files: Laravel Localization

In this step, we will create two routes one for display dashboard page with language dropdown and another for you can change language logic.

Create two routes in the routes/web.php file. This comes under the routes directory. One will be for the language dropdown display on dashboard while the other for logic of change language.

Route::get('lang/home', [LangController::class, 'main']);
Route::get('lang/change_lang', [LangController::class, 'change_lang'])->name('changeLang');

You can add the routes with the get method, as shown above. Both methods are defined in the same LangController.

Step 3: Create a new LangController: Laravel Localization

The LangController manages the functions defined in the route file. It handles the dropdown display of language and the language change functionality.

  public function main()
    {
        return view('lang');
    }

The code above is to return the languages in view.

public function change_lang(Request $request)
    {
        App::setLocale($request->lang);
        session()->put('locale', $request->lang);
  
        return redirect()->back();
    }

The change_lang function sets the new locale as the language selected. It does this using the setLocale() function. It returns back the same view with the new language selected.

This sets the application language to the language selected and changes layout of all strings within the language file arrays.

Step 4: Create a View: Laravel LocalizationLaravel Localization

A view designs the layout of the language dropdown feature, created in Laravel Localization.

A lang.blade.php file should be created under the resources/views directory.

<body>
    <div class="container">
  
        <h1>Laravel Localization and multi-language support</h1>
  
        <div class="row">
            <div class="col-md-2 col-md-offset-6 text-right">
                <strong>Select a Language: </strong>
            </div>
            <div class="col-md-4">
                <select class="form-control changeLang">
                    <option value="en" {{ session()->get('locale') == 'en' ? 'selected' : '' }}>English</option>
                    <option value="fr" {{ session()->get('locale') == 'fr' ? 'selected' : '' }}>France</option>
                </select>
            </div>
        </div>
    
        <h1>{{ __('welcome.welcome_message') }}</h1>
     
    </div>
</body>
  
<script type="text/javascript">
  
    var url = "{{ route('changeLang') }}";
  
    $(".changeLang").change(function(){
        window.location.href = url + "?lang="+ $(this).val();
    });
  
</script>

The code above shows the language change div. Therefore, the user has options under a select dropdown to choose either English or French. The selected language is passed to the change function and appended to the URL.

Language files, i.e. welcome.php then displays a heading in the selected language, reading from the welcome message array.

Step 5: Create New Middleware: Laravel Localization

Dynamic language change is handled by a middleware. This is created under app/Http/Middleware directory and names as LanguageManager.php.

public function handle($request, Closure $next)
    {
        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        }
          
        return $next($request);
    }

It checked if the current session has the selected locale using the has() function. Then sets the current session locale for the Laravel application using App::setLocale function.

Step 6: Kernel File Update: Laravel Localization

Lastly, the new middleware should be added to the Kernel file.

 protected $middlewareGroups = [
        'web' => [
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\LanguageManager::class,
        ],
  
        'api' => [
            'throttle:60,1',
        ],
    ];

In this tutorial, you we learnt by example how to perform Laravel localization and use it in your application for multiple languages support. Moreover, it explains how to work with translation files, create a language switcher, and more with localization and multi-language examples.

Localization is the second phase of the Laravel internationalization process. Therefore, it designs an application to fit various languages and cultures.

Refer to Lang Directory Updates, if you are using Laravel 9.