How to use localization in laravel multilanguage support

How to use localization in laravel multilanguage support

In this article let’s understand How to use localization in laravel multilanguage support. Let’s understand through steps:

  • Create language files
  • Create and configure middleware
  • Create route – controller – view
  • Add translations to lang files
  • Result

Step 1 : Create local files

First of all lets create language files at resources/lang/{en.json, fr.json}. Checkout below structure.

/lang
    /en.json
    /fr.json

Configure and check locale at “config/app.php”

.
.
'locale' => 'en',
'fallback_locale' => 'en',
.
.
  • The application locale determines the default locale that will be used by the translation service provider.
  • The fall-back locale determines the locale to use when the current one is not available.

Step 2 : Create middleware

We need to apply this middleware to filter out routes that will use localization functionality we will create. Create one at app/Http/Middleware/Localization.php as below:

  • Basically this middleware will set the value from session. So we will update the session value while switching the language and it will take care of the rest.
<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Session;


class Localization
{
    public function handle(Request $request, Closure $next)
    {
        if (Session::has('locale')) {
            \App::setLocale(Session::get('locale'));
        }
        return $next($request);
    }
}

We will add the middleware in our kernal file to apply this to each and every request. Add as below at app\Http\Kernel.php

 protected $middlewareGroups = [
        'web' => [
           .
           .
            \App\Http\Middleware\Localization::class,

           .
        ],

Step 3 : Create route – controller – view

Lets create two routes first at \routes\web.php as below:

Route::get('locale', [LocaleController::class, 'view'])->name('locale');
Route::get('change-locale', [LocaleController::class, 'changeLocale'])->name('changeLocale');
  • locale‘ – We will use for our main view
  • change-locale’ – We will use to switch the language

Lets create our controller now at app\Http\Controllers\LocaleController.php as below:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class LocaleController extends Controller
{
    public function view()
    {
        return view('locale');
    }
    public function changeLocale(Request $request)
    {
        $validated = $request->validate([
            'locale' => 'required',
        ]);
        \Session::put('locale', $request->locale);
        return redirect()->back();
    }
}
  • view() – We are simply loading a view from blade file.
  • changeLocale() – Using it to get the requested language and update session.

Next, let’s create our view file as below at laravel\resources\views\locale.blade.php

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

        <title>Laravel</title>

        <!-- Fonts -->
        <link rel="preconnect" href="https://fonts.bunny.net">
        <link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <!-- Styles -->
        <style>
          * {
                box-sizing: border-box;
                }
                body {
                font-family: Arial, Helvetica, sans-serif;
                }
                header {
                background-color: #666;
                padding: 30px;
                text-align: center;
                font-size: 35px;
                color: white;
                }
                article {
                background-color: #f1f1f1;
                height: 300px;
                padding:20px;
                text-align:center;
                }
                footer {
                background-color: #777;
                padding: 10px;
                text-align: center;
                color: white;
            }
        </style>
    </head>
    <body>
        <header>
            <h2>{{ __('welcome_home')}}</h2>
            <select class="form-select p-3" name="locale" style="width: 10%;">
                <option value="en" {{ Lang::locale() == 'en' ? 'selected' : '' }}>English</option>
                <option value="fr" {{ Lang::locale() == 'fr' ? 'selected' : '' }}>French</option>
            </select>
        </header>
        <section>
            <article>
                <h3 style="margin:0">{{ __('welcome_home')}}</h3>
                <p>{{ __('text')}}</p>
            </article>
        </section>
        <footer>
            <p>{{ __('thank_you')}}</p>
        </footer>
        <script type="text/javascript">
            $(document).ready(function() {
                $('select[name=locale]').change(function() {
                    window.location.href = "{{ route('changeLocale') }}?locale="+ $(this).val();
                });
            });
        </script>
    </body>
</html>
  • Create few html blocks that represents translation
  • Will use select dropdown to switch between languages
  • Set javascript to call route on change event of language
  • Use syntax {{ __(‘text’)}} where text will represent the key from json file.

Step 4 : Add translations to lang files

laravel\resources\lang\en.json

{
    "welcome_home":"Welcome Home",
    "text":"Home, a word that holds immense significance and embodies a sense of belonging, comfort, and love. It is a place where we can truly be ourselves, where our joys and sorrows are shared, and where lasting memories are created.",
    "thank_you":"Thank you"
}

laravel\resources\lang\fr.json

{
    "welcome_home":"Bienvenue à la maison",
    "text":"Accueil, un mot qui a une immense signification et incarne un sentiment d'appartenance, de confort et d'amour. C'est un endroit où nous pouvons vraiment être nous-mêmes, où nos joies et nos peines sont partagées et où des souvenirs durables sont créés.",
    "thank_you":"Merci"
}

Step 5 : Result

Head to route “http://localhost:8000/locale” and check result

Switch the language from header and see result:

That’s all on How to use localization in laravel multilanguage support. Hope this easy article finds you helpful.

Checkout more articles on Laravel here.