Search

Laravel 8 Create Multi Language Website

post-title

Laravel provides easy way to create multilingual website. Laravel provides two ways to manage language strings. First one is store different language strings in resources/lang directory. Second way is to create create Json file for every language in resources/lang directory.

In this article, we will use Json file approach to create multilingual website. This way is recommended when you have large number of translate strings. We will create application step by step from the scratch. So let's start.

Step 1: Create Laravel application

In the first step, we will create fresh Laravel application using composer command. So open Terminal and run the below command to create new Laravel application.

composer create-project laravel/laravel language

Now go to the project directory

cd language

Step 2: Create language files

We have created the Laravel application. Now we need to create all language files that we are using. In this article, we will use English, Spanish German and Hindi languages. So create Json files for this languages.

/resources
    /lang
        en.json
        es.json
        de.json
        hi.json

Now put the json arrays in these files.

en.json

{
    "Sign in": "Sign in",
    "Email address": "Email address",
    "Password": "Password"
}

es.json

{
    "Sign in": "Registrarse",
    "Email address": "Dirección de correo electrónico",
    "Password": "Contraseña"
}

de.json

{
    "Sign in": "Einloggen",
    "Email address": "E-Mail-Addresse",
    "Password": "Passwort"
}

hi.json

{
    "Sign in": "साइन इन करें",
    "Email address": "ईमेल पता",
    "Password": "कुंजिका"
}

Step 3: Create route and Controller file

We have created Json files for different languages. Now we need to create routes for view and change language. So open routes/web.php file and add two routes in it.

<?php

use App\Http\Controllers\LanguageController;

Route::get('view', [LanguageController::class, 'view'])->name('view');
Route::get('language-change', [LanguageController::class, 'changeLanguage'])->name('changeLanguage');

We will need to create controller class. Run the below artisan command to create controller.

php artisan make:controller LanguageController

This will create controller class at app/Http/Controllers/LanguageController.php file. Open this file and add two methods to handle the routes.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class LanguageController extends Controller
{
    /**
     * return view
     *
     * @return view
     */
    public function view()
    {
        return view('language');
    }

    /**
     * Change language
     *
     * @param  \Illuminate\Http\Request $request
     * @return void
     */
    public function changeLanguage(Request $request)
    {
        $validated = $request->validate([
            'language' => 'required',
        ]);

        \Session::put('language', $request->language);

        return redirect()->back();
    }
}

Step 4: Create and register middleware

In this step, we will create middleware which will manage language for all routes. So create middleware with below command.

php artisan make:middleware Language

Now open this middleware file app/Http/Middleware/Language.php and change its code.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Language
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (\Session::has('language')) {
            \App::setLocale(\Session::get('language'));
        }
        return $next($request);
    }
}

We will also need to register middleware in app/Http/Kernel.php file. So add this middleware in  $middlewareGroups variable's web array.

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    ...

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    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\Language::class,
        ],

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

Step 5: Create blade view

In this last step, we create the blade file for language change. Create blade file at /resources/views/language.blade.php file and put the below HTML code in it.

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <style type="text/css">
        html,
        body {
          height: 100%;
          background-color: #f5f5f5;
        }
        .main-container {
          display: flex;
          align-items: center;
          padding-top: 40px;
          padding-bottom: 40px;
        }
        .form-signin {
          width: 100%;
          max-width: 330px;
          padding: 15px;
          margin: auto;
        }
    </style>
</head>
<body>
    <div class="text-right m-3">
        <select class="form-select p-3" name="language" style="width: 10%;">
            <option value="en" {{ \Session::get('language') == 'en' ? 'selected' : '' }}>English</option>
            <option value="es" {{ \Session::get('language') == 'es' ? 'selected' : '' }}>Spanish</option>
            <option value="de" {{ \Session::get('language') == 'de' ? 'selected' : '' }}>German</option>
            <option value="hi" {{ \Session::get('language') == 'hi' ? 'selected' : '' }}>Hindi</option>
        </select>
    </div>
    <div class="main-container">
        <main class="form-signin">
            <form class="text-center">
                <h1 class="h3 mb-3 fw-normal">{{ __('Sign in') }}</h1>
                <div class="form-floating">
                    <input type="email" class="form-control m-1" id="email" placeholder="name@example.com">
                    <label for="email">{{ __('Email address') }}</label>
                </div>
                <div class="form-floating">
                    <input type="password" class="form-control m-1" id="password" placeholder="******">
                    <label for="password">{{ __('Password') }}</label>
                </div>
                <button class="w-100 btn btn-lg btn-primary m-1" type="submit">{{ __('Sign in') }}</button>
            </form>
        </main>
    </div>
    <script type="text/javascript">
        $(document).ready(function() {
            $('select[name=language]').change(function() {
                var lang = $(this).val();
                window.location.href = "{{ route('changeLanguage') }}?language="+lang;
            });
        });
    </script>
</body>
</html>

Now everything is done. Run the Laravel server with artisan command php artisan serve. Open the browser and go to the page http://localhost:8000/view. In the left corner change language select drop-down. The language will change according it.

Conclusion

This way, you can create multilingual website in Laravel 8. I hope you liked this article and it will help on your way.