Localization laravel

狂风中的少年 提交于 2019-12-24 05:16:05

问题


I have been trying to update language for the website.

Controller

public function getUpdateLanguage(Request $request) {
        $request_data = $request->all();
         \Session::put('locale', $request_data['language']);
        return redirect()->back();
}

Middleware:

 public function handle($request, Closure $next)
 { 
    if ( \Session::has('locale')) {
        \App::setLocale(\Session::get('locale'));
    }
    return $next($request);
 }

But the true block for if ( \Session::has('locale')) never executes and the language is always 'en' and never updates. It works fine if I try

 public function handle($request, Closure $next)
 { 

     \App::setLocale('arabic');

    return $next($request);
 }

kernel:

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\Localization::class,
    ];

Localization is my middleware. The language update controller method redirects to home:

public function getIndex() {
        return view('frontend.home');
}

Can someone please guide me where is the session value being cleared or if I am doing it wrong and there is a better way?


回答1:


Add \Illuminate\Session\Middleware\StartSession::class to your middleware array in kernel.php:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\Localization::class,
];



回答2:


You could do something like that

Middleware :

public function handle($request, Closure $next)
 { 
    App::setLocale(
        $request->session()->has('locale') ? 
        $request->session()->get('locale') : 
        App::getLocale()
    );

    return $next($request);
 }


来源:https://stackoverflow.com/questions/48607759/localization-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!