Laravel 5.8 setLocale globally

前端 未结 3 676
失恋的感觉
失恋的感觉 2021-01-03 09:31

I have a route:

    Route::get(\'/setlocale/{locale}\', function($locale) {
            App::setLocale($locale);

            


        
3条回答
  •  再見小時候
    2021-01-03 10:15

    Try this way

    1. firstly when user choose a language we put our selected locale(language) in session [example en, fr, hi ]

    
    Route::get('setlocale/{locale}',function($lang){
           \Session::put('locale',$lang);
           return redirect()->back();   
    });
    

    2. Second We use a middleware for translating pages according to our session locale (user selected)

    3. Third we put this middleware in kernel.php routeMiddleware (app/Http/kernel.php)

    protected $routeMiddleware = [
            'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
            'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
            'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
            'can' => \Illuminate\Auth\Middleware\Authorize::class,
            'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
            'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
            'language' => \App\Http\Middleware\LanguageSwitcher::class,        
        ];
    
    'language' => \App\Http\Middleware\LanguageSwitcher::class,
    

    4. Fourth, serving this middleware we need route group. so each request goes through this middleware

    Route::group(['middleware'=>'language'],function ()
    {
        //your translation routes
    });
    

    Logic in middleware

    In middleware for every request we check if locale set in current session or not. if Session not having locale then for current request we set locale to config locale means in your app configuration locale

    'locale' => 'en',  // config/app.php
     Session::put('locale',Config::get('app.locale')); // in middleware code we use Config method to get app configuration locale
    App::setLocale(session('locale')); // finally set this to App locale
    

    else if we have locale in current session then we set that to App locale

    App::setLocale(session('locale')); // set this to App locale
    

提交回复
热议问题