laravel 5.5 在构造函数中获取用户详细信息

Has*_*ilT 10 php laravel laravel-5.5

我正在构建一个具有多个用户角色和操作的应用程序。我确实遵循了laravel 官方文档(https://laravel.com/docs/5.5/middleware#middleware-parameters)。

但是在我的控制器的构造函数中(从我调用上面的中间件的地方)我使用 Auth 外观来获取用户详细信息。我知道如何使用 Auth 门面,我已经在我的应用程序中的几个地方实现了它。但是当我在构造函数中使用它时,它返回 null(在登录条件下 - 我仔细检查过)。

我是这样实现的,我必须调用两个控制器(因为只有注册用户才能访问该页面)

public function __construct()
{
    $role = Auth::user()->role;
    $this->middleware('auth');
    $this->middleware('checkRole:$role');
}
Run Code Online (Sandbox Code Playgroud)

PS:我尝试将 $role 变量初始化为 protected 并且在构造函数之外,仍然无法正常工作。任何建议都会有所帮助

谢谢你。

小智 13

那是因为构造函数是在中间件之前创建的,这就是它返回 null 的原因。

这个答案很可能会解决您的问题:Can't call Auth::user() on controller's constructor


小智 5

如果您对“前端”用户和“管理员”使用相同的用户表并希望在管理员控制器的构造函数中应用条件。

您可以在下面使用。

auth()->user()
Run Code Online (Sandbox Code Playgroud)

在构造函数中,您可以使用以下代码。

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);
    });
}
Run Code Online (Sandbox Code Playgroud)

但我更喜欢在单独的中间件类中处理这些,而不是在控制器构造函数中编写它。