问题
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