2
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.

francisco
  • 1,387
  • 2
  • 12
  • 23
Mario
  • 21
  • 3
  • Your code is probably working fine, it's just VSCode doesn't understand it. You may need to install a Laravel extension for code hints. – aynber Apr 18 '23 at 12:00

2 Answers2

1

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')) {
    // ...
}
Gleb Kemarsky
  • 10,160
  • 7
  • 43
  • 68
0

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

Amir
  • 86
  • 7