laravel 5.5 在构造函数中获取用户详细信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46161126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel 5.5 Get user details inside constructor
提问by HasilT
I am building an application with multiple user roles and actions. I did follow the official laravel doc (https://laravel.com/docs/5.5/middleware#middleware-parameters).
我正在构建一个具有多个用户角色和操作的应用程序。我确实遵循了官方 laravel 文档(https://laravel.com/docs/5.5/middleware#middleware-parameters)。
But in my controller's constructor (from where I call the above middleware) I am using Auth facade to get user details. I know how to use Auth facade, I had implemented it on several places inside my application. But when I use it inside the constructor it returns null (in logged in condition - I double checked that).
但是在我的控制器的构造函数中(从我调用上述中间件的地方),我使用 Auth 外观来获取用户详细信息。我知道如何使用 Auth facade,我已经在我的应用程序中的几个地方实现了它。但是当我在构造函数中使用它时,它返回 null(在登录条件下 - 我仔细检查过)。
I implemented it like this, I have to call two controllers(since only registered users can access that page)
我是这样实现的,我必须调用两个控制器(因为只有注册用户才能访问该页面)
public function __construct()
{
$role = Auth::user()->role;
$this->middleware('auth');
$this->middleware('checkRole:$role');
}
PS: I tried to initialize $role variable as protected and outside the constructor , still not working. Any suggestions will be helpful
PS:我尝试将 $role 变量初始化为 protected 并且在构造函数之外,仍然无法正常工作。任何建议都会有所帮助
Thank you.
谢谢你。
回答by taavs
That's because constructors are created before middlewares,that's why its returning null.
那是因为构造函数是在中间件之前创建的,这就是它返回 null 的原因。
This answer will propably solve your problems: Can't call Auth::user() on controller's constructor
这个答案很可能会解决您的问题:Can't call Auth::user() on controller's constructor
回答by Mahesh Yadav
If you are using the same user table for both "front-end" user and "admin" & want to apply condition in admin controller's constructor.
如果您对“前端”用户和“管理员”使用相同的用户表并希望在管理员控制器的构造函数中应用条件。
You can use below.
您可以在下面使用。
auth()->user()
And in the constructor you can use below code.
在构造函数中,您可以使用以下代码。
public function __construct(){
$this->middleware(function ($request, $next) {
if(auth()->user()->hasRole('frontuser')){
return redirect()->route('home')->withFlashMessage('You are not authorized to access that page.')->withFlashType('warning');
}
return $next($request);
});
}
But I prefer to handle these in separate middleware class instead of writing this in the controllers constructor.
但我更喜欢在单独的中间件类中处理这些,而不是在控制器构造函数中编写它。