I have a request with an authorize method that makes use of:
Illuminate\Http\Request::user()
And it gives me a phpstan error that says
phpstan: Cannot call method hasAnyRole() on App\Models\User|null.
And that makes sense.
So I made an abstract class that makes use of
Illuminate\Http\Request::user()
like this:
<?php
namespace App\Http\Requests;
use App\Models\User;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Http\FormRequest;
abstract class VbpRequest extends FormRequest
{
/**
* Get the user making the request.
*
* @param string|null $guard
* @return User
* @throws AuthenticationException
*/
public function user($guard = null): User
{
$user = parent::user($guard);
if ($user instanceof User) {
return $user;
}
throw new AuthenticationException('Trying to resolve a user, but no one is logged in.');
}
}
In theory this should only return an instance of the User model or an exception.
but when I use this new method it gives me the exact same phpstan warning.
phpstan: Cannot call method hasAnyRole() on App\Models\User|null.
Does anyone have an idea of what is going wrong or could be going wrong?
Here is the Request:
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use App\Models\Role;
use App\Traits\RequestCast;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Validation\Rule;
class BelnotitieRequest extends VbpRequest
{
use RequestCast;
/**
* @throws AuthenticationException
*/
public function authorize(): bool
{
return $this->user()->hasAnyRole(Role::ADMIN_ID, Role::PROJECTMANAGER_ID, Role::ADMINISTRATIEF_MEDEWERKER_ID);
}
}
I'm using Laravel 9.24 and larastan 2.1.12