Laravel Localization – Multi Language Website

0
1283
Laravel Localization

In this tutorial, you’ll learn how to create an application that is in multiple languages. Laravel localization is a convenient way to do that. Besides, translations are strings that are stored in a file as a key-value pair. Laravel provides English(en) as the default language(locale) that are stored in resources > lang folder. Folders in lang folders are language codes to define translation files. Above all, you can find the official documentation here.

I assume that you have basic knowledge of laravel and you already installed it. If you don’t know how to install Laravel then click here. I’m using laravel 8 here.

We’ll use English(en), Spanish(es), German(de) language for this tutorial. There are two ways to create translation files. Either you can create a subdirectory of each language code, and in each subdirectory, there are .php files to define translation strings. For example:

resoures > lang > en > pages.php
resoures > lang > es > pages.php
resoures > lang > de > pages.php

Or, you can directly create a .json file with language code.

resources > lang > en.json
resources > lang > es.json
resources > lang > de.json

I’ll use the first approach for this tutorial because it provides structural code. But you can use any of them. So let’s get started.

# Creating Translation Files

Firstly, create three translation files and enter translation strings. Keep in mind, all of the keys from all translation files must be the same. You can access these keys with @lang() or trans() or __() function in blades, controllers etc.

/* resources > lang > en > pages.php */

<?php

return [
    'welcome-to-home-page' => 'Welcome To Home Page',
    'welcome-to-contact-page' => 'Welcome To Contact Page',
    'choose-language' => 'Choose Language',
];
/* resources > lang > es > pages.php */

<?php

return [
    'welcome-to-home-page' => 'Bienvenido a la página de inicio',
    'welcome-to-contact-page' => 'Bienvenido a la página de contacto',
    'choose-language' => 'Elige lengua'
];
/* resources > lang > de > pages.php */

<?php

return [
    'welcome-to-home-page' => 'Willkommen auf der Homepage',
    'welcome-to-contact-page' => 'Willkommen auf der Kontaktseite',
    'choose-language' => 'Sprache wählen',
];

# Creating Views

Next, create the necessary view for this application. Let’s create a layout file along with the home and contact page. To do that, create app.blade.php inside resources > views > layouts. The layout file contains basic page navigation and language dropdown.

/* resources > views > layouts > app.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">

    <!-- 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">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div id="app">
    <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
        <div class="container">

            <ul class="navbar-nav mr-auto">
                <li class="nav-item dropdown">
                    <a href="{{ route('home') }}" class="nav-link @if(Route::currentRouteName()=='home') active @endif">Home</a>
                </li>
                <li class="nav-item dropdown">
                    <a href="{{ route('contact') }}"
                       class="nav-link @if(Route::currentRouteName()=='contact') active @endif">Contact</a>
                </li>
            </ul>

            <ul class="navbar-nav ml-auto">
                <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>
                        @lang("pages.choose-language") - {{ app()->getLocale() }}
                    </a>

                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
                        <a class="dropdown-item" href="{{ url('lang/en') }}">English</a>
                        <a class="dropdown-item" href="{{ url('lang/es') }}">Español</a>
                        <a class="dropdown-item" href="{{ url('lang/de') }}">Deutsche</a>
                    </div>
                </li>
            </ul>
        </div>
    </nav>

    <main class="py-4">
        @yield('content')
    </main>
</div>
</body>
</html>

After that, create two pages home and contact.

/* resources > views > home.blade.php */

@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">
                        @lang("pages.welcome-to-home-page")
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
/* resources > views > contact.blade.php */

@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">
                        @lang("pages.welcome-to-contact-page")
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

# Creating Controller & Routes

Now create a controller with the following command and add two methods for the home and contact page. Also, you need to add routes to the routes > web.php for the page. I’m adding a third route with {lang} parameter that contains language code. This route will set a given locale when the user changes it from the dropdown from the navigation.

php artisan make:controller PageController
/* app > Http > Controllers > PageController.php */

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PageController extends Controller
{
    public function index() {
        return view('home');
    }

    public function contact() {
        return view('contact');
    }
}
/* routes > web.php */

<?php

use Illuminate\Support\Facades\Route;

Route::group(['namespace' => 'App\Http\Controllers'], function () {
    Route::get('/', 'PageController@index')->name('home');
    Route::get('/contact', 'PageController@contact')->name('contact');
});


Route::get("lang/{lang}", function ($lang) {
    app()->setLocale($lang);
    session()->put('locale', $lang);
    return redirect()->back();
});

# Creating Middleware

Finally, create SetLocale middleware. It will check for locale and set it to every HTTP request before entering your application. Also, add an entry of SetLocale middleware into kernel.php in the $middlewareGroups array.

php artisan make:middleware SetLocale
/* app > Http > Middleware > SetLocale.php */

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SetLocale
{
    public function handle(Request $request, Closure $next)
    {
        if (session()->has('locale')) {
            app()->setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}
/* app > Http > Kernel.php */

<?php     
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\SetLocale::class,
    ],

    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

In the end, visit http://localhost:8000/ from the browser with navigating pages and with changing languages.

That’s all for laravel localization. Thank you for reading this tutorial. Please share and comment for support.

Learn more about Laravel Framework

LEAVE A REPLY

Please enter your comment!
Please enter your name here