Laravel 5.4存储语言环境setLocale()的正确方法 [英] Laravel 5.4 proper way to store Locale setLocale()
问题描述
我需要知道.为用户存储区域设置的正确方法是什么?如果我根据每个用户的要求更改语言,则
I need to know. What is the proper way to store Locale for user. If for each users' request I change the language by
App::setLocale($newLocale);
是否会更改整个项目以及其他要求的语言?我的意思是,当一个用户更改语言时,它将被其他用户用作默认语言.
Would not it change language for my whole project and for other requests as well? I mean when one user changes language it will be used as default for other users.
预先感谢
推荐答案
例如,如果在AppServiceProvider.php
中设置了App::setLocale()
,它将对所有用户更改.
If you set App::setLocale()
in for example in your AppServiceProvider.php
, it would change for all the users.
您可以为此创建一个中间件.像这样:
You could create a middleware for this. Something like:
<?php
namespace App\Http\Middleware;
use Closure;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
app()->setLocale($request->user()->getLocale());
return $next($request);
}
}
(您需要在User模型上创建一个getLocale()
方法,该方法才能起作用.)
(You need to create a getLocale()
method on the User model for this to work.)
然后在Kernel.php
中为auth
创建一个中间件组:
And then in your Kernel.php
create a middleware group for auth
:
'auth' => [
\Illuminate\Auth\Middleware\Authenticate::class,
\App\Http\Middleware\SetLocale::class,
],
并从$routeMiddleware
数组(在您的Kernel.php
中)中删除auth
.
And remove the auth
from the $routeMiddleware
array (in your Kernel.php
).
现在,在使用auth
中间件的每条路由上,您都将为每个用户设置Laravel应用程序的语言环境.
Now on every route that uses the auth
middleware, you will set the Locale of your Laravel application for each user.
这篇关于Laravel 5.4存储语言环境setLocale()的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!