Tag Archive for: RTL

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.