Home > Back-end >  How to change locale in laravel route?
How to change locale in laravel route?

Time:03-04

I am working on Laravel localization. I have all done but facing issue. When I change language from dropdown page successfully transalated but language in ROUTE not change.

In web.php I have setup this,

Route::get('/', function () {
    return redirect(app()->getLocale());
});
Route::get('language/change', [LocalizationController::class, 'changeLanguage'])->name('changeLang');
Route::group(
    [
        'prefix' => '{locale}',
        'where' => ['locale' => '[a-zA-Z]{2}'],
        'middleware' => 'setlocale'
    ],function () {

    Route::get('/', [MainController::class, 'index'])->name('main.index');
    Auth::routes();
    Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
    Route::group(['middleware' => ['auth']], function () {
        //
    });
});

I have added below code in Middleware,

public function handle(Request $request, Closure $next)
{
    if (session()->has('locale')) {
        App::setLocale(session()->get('locale'));
    }
    return $next($request);
}

In view file I have added this code,

<select >
        <option {{ session()->get('locale') == 'en' ? 'selected' : '' }} value="en">           
  • Related