【问题标题】:Laravel 10 Auth::user() - Attempt to read property on nullLaravel 10 Auth::user() - 尝试读取 null 上的属性
【发布时间】:2023-02-24 05:43:54
【问题描述】:

我想要做的就是制作一个中间件,只有 role_id = 1 的用户才能访问仪表板。

请记住,我没有使用laravel/breeze,而是使用了laravel/ui auth

这是我的 checkRole 中间件:

public function handle(Request $request, Closure $next): Response
{
    if(Auth::user()->role_id != 1)
    {
        return redirect()->route("welcomepage");
    } 

    return $next($request);

}

这是web.php 中的中间件:

Route::middleware(["checkRole"])->group(function() {
    Auth::routes(["register" => false, "reset" => false]);
    //I use these parameters because i don't want these routes
});

我之前在laravel/breeze 上使用过相同的中间件并且没有问题,但现在在laravel/ui auth 上我得到了这个错误。

【问题讨论】:

    标签: php laravel authentication middleware roles


    【解决方案1】:

    当我输入问题时,我随机提出了​​解决方案。构造方法中的laravel/ui auth中的laravel/ui auth是列出的中间件

    这是它现在的样子:

    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('checkRole'); //just added it
    }
    

    web.php 中,我刚刚删除了中间件并且只有:

    Auth::routes(["register" => false, "reset" => false]);
    

    中间件方法保持不变。

    【讨论】:

      猜你喜欢
      • 2022-10-12
      • 2022-11-16
      • 2022-01-04
      • 2021-06-25
      • 2023-01-28
      • 2023-01-25
      • 2018-03-07
      • 2021-05-25
      • 2022-06-10
      相关资源
      最近更新 更多