Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

Making PHPStan properly recognize the authenticated user

Without adding docblocks everywhere

Joel Clermont
Joel Clermont
2025-11-18

From our daily Laravel tips email. Get the next one in your inbox.

If you've ever used PHPStan in a Laravel project, you might have been frustrated at how certain types are resolved.

A common complaint is with the authenticated user. A simple call like $request->user() will evaluate as returning mixed, and Auth::user() will evaluate as Illuminate\Contracts\Auth\Authenticatable|null.

Neither of these are helpful if you want to go on and use that return type as a User model.

To be clear, this is not a problem with PHPStan, but rather with how the Laravel types are actually expressed in the framework code.

The solution is easy, though: Install Larastan instead of PHPStan. It brings in PHPStan along with a set of extensions specifically for Laravel.

One important note: Just installing the package isn't enough. You need to also add Larastan's extension to your phpstan.neon configuration file.

With that installed, both $request->user() and Auth::user() will be properly recognized as returning your User model. Even better, if you have a different model or guard set up in your config/auth.php, Larastan is smart enough to resolve that instead.

And this is just one of dozens of Laravel-specific improvements that Larastan provides over vanilla PHPStan.

Here to help,

Joel

P.S. I've helped a lot of teams get started with static analysis in Laravel projects. Would you like help on your project?

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.