在 null 上调用成员函数 hasAnyRole()

Call to a member function hasAnyRole() on null

我是 laravel 的新手。我的中间件实际上有问题。我已经在 Kernel.php 文件中注册了它。

public function handle($request, Closure $next){

   $user = Auth::user();

    if($user->hasAnyRole('school'))
    {
         return $next($request);
    }
      

    return redirect('login');
}

这是我的用户模型

public function roles(){

        return $this->belongsToMany('App\Role');
    }

    public function hasAnyRoles(){

        return null !== $this->roles()->whereIn('name', $roles)->first();
    }

     public function hasAnyRole(){
     return null !== $this->roles()->where('name', $role)->first();
     }

尝试翻转逻辑并检查是否已登录。 做一个 (Auth::check() :

public function handle($request, Closure $next){
  if (Auth::check()) {
     $user = Auth::user();
     if($user->hasAnyRole('school'))
     {
        return $next($request);
     }
  } else {
      return redirect('login'); 
  }
}