DEV Community

Jérôme W
Jérôme W

Posted on • Edited on

How to create a multilingual project in Laravel 8 (i18n)

Alt Text

This tutorial explains how to create a language system and be able to change the language in the menu with the corresponding translations.

I will try to be clear and concise 😃

Check out a Spanish translation here

Setup

First, you need to create a controller App/Http/Controllers to record the language in session and be able to retrieve it with the middleware we will create just after :

namespace App\Http\Controllers;

use App;
use Illuminate\Http\RedirectResponse;

class LocalizationController extends Controller
{
    /**
     * @param $locale
     * @return RedirectResponse
     */
    public function index($locale)
    {
        App::setLocale($locale);
        session()->put('locale', $locale);
        return redirect()->back();
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, you must create a middleware App/Http/Middleware to retrieve the language that was recorded in session :

namespace App\Http\Middleware;

use App;
use Closure;

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

After that, you must save the middleware in app/http/Kernel.php :

    /**
     * The application's route middleware groups.
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            (...)
            \App\Http\Middleware\Localization::class,
        ],

        (...)
    ];
Enter fullscreen mode Exit fullscreen mode

Finaly, create a route to change the language :

use App\Http\Controllers\LocalizationController;

Route::get('lang/{locale}', [App\Http\Controllers\LocalizationController::class, 'index']);
Enter fullscreen mode Exit fullscreen mode

Create the dropdown

First, you must create a flag folder in public/images and store flags images inside :
Alt Text

Secondly, in your menu, insert this code to be able to switch from one language to another :

@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>
        @switch($locale)
            @case('en')
            <img src="{{asset('images/flag/en.png')}}" width="25px"> English
            @break
            @case('fr')
            <img src="{{asset('images/flag/fr.png')}}" width="25px"> Français
            @break
            @default
            <img src="{{asset('images/flag/en.png')}}" width="25px"> English
        @endswitch
        <span class="caret"></span>
    </a>
    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
        <a class="dropdown-item" href="lang/en"><img src="{{asset('images/flag/en.png')}}" width="25px"> English</a>
        <a class="dropdown-item" href="lang/fr"><img src="{{asset('images/flag/fr.png')}}" width="25px"> Français</a>
    </div>
</li>
Enter fullscreen mode Exit fullscreen mode

Let's try it

To test that everything works, insert this code on your homepage or any other page :

<h1>@lang("Bonjour")</h1>
Enter fullscreen mode Exit fullscreen mode

Then to finish, in the resources/lang folder, you have to create a folder for each language you want (for example fr and en) and for each folder, do the following to take into account the text of the homepage to translate :

<?php
// EN folder
return [
    'Bonjour' => 'Hello'
];
Enter fullscreen mode Exit fullscreen mode

Here we go, now if you click on the english flag in your menu, the Bonjour text will change to Hello.

Notice that if you need, there is another way to make translations using json :

{
    "Bonjour" : "Hello"
}
Enter fullscreen mode Exit fullscreen mode

The final word 💬

Thanks for reading this little tutorial, feel free to add a comment to share your opinions! 😀☕

If you're looking for a lot a flags, I have a repository with :

  • 284 flags of countries and unions all over the world
  • With name France.png or ISO 3166-1 alpha-2 codes fr.png
  • Available sizes: 16×16, 24×24, 32×32, 48×48, 64×64, 128×128
  • Icon formats: PNG

If you want more informations about localization, you can refer in official Laravel documentation : https://laravel.com/docs/8.x/localization

Top comments (3)

Collapse
 
benbigras profile image
Ben Bigras • Edited

I found the error, and fixed it. You need to begin with a forward slash both in your route and your menu... so
Route::get('/lang/{locale}
not
Route::get('lang/{locale}
and
href="/lang/en"
not
href="lang/en"

Collapse
 
benbigras profile image
Ben Bigras • Edited

this is my favourite way to do it after reading the instructions, however I found that you get a 404 error when a parameter is used in the URL. If I have a route that goes something like example.com/user/1 where 1 is the id of the user, the code breaks and instead of the translation occurring you get a 404... any fix for this?

Collapse
 
maninthehood profile image
maninthehood

Hey there Ben Bigras, its Carlos Kirui from Dev.to. Welcome to Dev.to, here you can share and explore your wildest programming ideas. your post was really enticing and interesting. keep up with the good work and the effort of writing such post. Bye, hope to see u again