Localization in Laravel

To use localization first we need to store language in session for that we will write simple function in route/web.php

Route::get('/locale', function(){
session(['my_locale' => app('request')->input('locale')]);
return redirect()->back();

})->name('locale');

 

Create middleware SetLanguage

App::setLocale(session('my_locale', config('app.locale')));

return $next($request);

 

Add session and SetLanguage middleware to app/Http/Kernel.php in web 

\App\Http\Middleware\SetLanguage::class,

 

This are main task you can submit request to url /locale by form or by sending parameter through query string

It will change session my_locale and redirect and middleware SetLanguage will set locale as per session

 

I have used form and using livewire model input default session value set

public $locale;
public function mount(){
$this->locale = App::currentLocale();
}
public function render()
{
return view('livewire.locale.select');

}

 

form code

<form id="localeForm" action="{{ route('locale') }}">
<div class="col-auto ms-auto">
<label class="visually-hidden" for="locale">Locale</label>
<select name="locale" wire:model="locale" class="form-select form-select-sm" id="locale" onchange="document.getElementById('localeForm').submit()">
<option value="en">English</option>
<option value="hi">हिंदी</option>
</select>
</div>

</form>