I made a piece of middleware that is responsible to check the permission a user has. I implemented a hasPermission function in my User model. But when I try to use it via the auth()->user
I get the following error, why is this happening?
I implemented this method in my User Model
public function hasPermission($permission)
{
return in_array($this->permissions(), $permission);
}
And this is the middleware
<?php
namespace App\Http\Middleware;
use Closure;
class VerifyPermission
{
public function handle($request, Closure $next, $permission)
{
if (auth()->check() && auth()->user()->hasPermission($permission)) {
return $next($request);
}
abort(401, 'Unauthorized');
}
}
It's because the user()
method has a return type of \Illuminate\Contracts\Auth\Authenticatable|null
which is an interface that your user class implements. This is because it might return different models based on the guard you're using but they all have to implement Authenticatable
.
I'm not aware of an easy way to change this globally, but you could save the user in a variable and add a phpDoc block:
/** @var \App\User */
$user = auth()->user();
This should get picked up by intelephense and show the correct methods.