在laravel中为整个控制器分配用户值 [英] Assign user values for whole controller in laravel
问题描述
我正在开发我的第一个laravel应用,我想根据用户角色和ID在控制器上管理不同的操作.
I'm developing my first laravel app, and I want to manage different actions on my controllers depending on user role and id.
所以我想知道是否可以向我的控制器添加两个私有变量 $ userRole
和 $ userId
,这样我就不需要调用 auth()-> user()->角色
和 auth()-> user()-> id
.
So I'm wondering if I can add two private variables $userRole
and $userId
to my controller so I don't need to call auth()->user()->role
and auth()->user()->id
in each single action method.
我尝试在__construct方法上初始化变量,但是中间件此时似乎未处于活动状态,并且无法访问user()参数.
I've tried to initiate the variables on __construct method, but the middleware seems not to be active at this point, and cannot access user() parameters.
我也尝试只给变量赋 auth()-> user()->任何
,但是php似乎在编译时加载了这些值,因此方法无法用于初始化.
I've tried also to just assign my variables with the auth()->user()->whatever
, but seems that php load these values on compile time, so methods cannot be used for the initialization.
现在,我想知道是否应该为此创建自己的中间件(我将在几个不同的Controller类上使用它)还是应该使用会话.
Now I'm wondering if I should create my own middleware for this (I will use it on several different Controller classes) or if I should use sessions.
对此有何建议?
推荐答案
在创建控制器之前,会话中间件尚未运行.
The session middleware has not ran by the time your controller is created.
您可以添加一个控制器中间件,该中间件可以为您分配这些值,因为中间件将在堆栈中运行:
You can add a controller middleware that can assign these values for you, as the middleware will run in the stack:
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->userId = $request->user()->id;
$this->roleId = $request->user()->role;
return $next($request);
});
}
另一个类似的问答: Auth :: user()在新路由中为空
这篇关于在laravel中为整个控制器分配用户值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!