Skip to content
Najib Ahmed

Multi-language Laravel 8 project

This article was first published in 2022. Some details, versions and links may be out of date.

In this post, we are going to explain the shortest path to add many languages to Laravel 8 including RTL language and language switcher.

1- Add languages to app/config/app.php file

'languages' => [
        'ar', 'en'
    ],

2- Create middleware component

php artisan make:middleware Localization

3- Add Localization class to web group in app/kernal file

\App\Http\Middleware\Localization::class,

4- In app/http/middleware/Localization.php

public function handle(Request $request, Closure $next)
    {
        $languages = config('app.languages');
        $lang = session()->has('lang') ? session()->get('lang') : '';
        if (in_array($lang, $languages)) {
            App::setLocale($lang);
        }
        return $next($request);
    }

5- In the web routes add the following route

Route::get('lang/{locale}', function ($locale) {
    $languages = config('app.languages');
    if (in_array($locale, $languages)) {
        session()->put('lang', $locale);
    }
    return redirect()->back();
})->name('setlanguage');

6- Add languages switcher in the Navbar
@foreach (config('app.languages') as $locale) > a href="{{ route('setlanguage', $locale) }}" class=" {{ app()->getLocale() == $locale ? ' border dark:border-white border-gray-800' : '' }} p-1 m-1 rounded-md hover:text-white active:text-white focus:text-white"> @if ($locale == 'ar') AR flag @elseif($locale == 'en') EN flag @endif >/a> @endforeach

7- Add language file in lang folder
ar.json for example and add json array to it.

Done.

Written by Dr Najib Ahmed

I build academic and multilingual web platforms. If you need help with a project like this, get in touch.

About mePortfolio

Get in touch