Undefined method 'hasRole'.intelephense(1013)

1.1k Views Asked by At
if (auth()->check() && (auth()->user()->hasRole('Admin'))) {
    $people = Person::latest()->paginate(5);
} else {
    $people = Person::where('user_id', $user->id)->latest()->paginate(5);
}

My editor code analysis tool is not able to detect the method.Undefined method 'hasRole'.intelephense(1013)

The 'if' condition is working correctly.

2

There are 2 best solutions below

0
Gleb Kemarsky On

I have used this solution from GitHub:

Because if you use Auth::user() the extension does not know it's actually a user model.

  1. let independence know that we use an instance of the User model: /** @var \App\Models\User */;
  2. define the $user variable as a result of auth()->user() or Auth::user();
  3. use $user->hasRole() in your code.
/** @var \App\Models\User */
$user = auth()->user();  // or Auth::user()
if ($user->hasRole('YourRole')) {
    // ...
}
0
Amir On

Actually, that happened because the code analysis tool you are using doesn't know that it is a user model. you could define the authenticated user to a variable like so

$user = Auth::user();

and then use it with hasRole like so

$user->hasRole('role')

source: https://github.com/bmewburn/vscode-intelephense/issues/1051#issuecomment-629142709