juhasev's avatar

Laravel model type hints

Hi there,

What is the best way of handling models with relations loaded in type hints? Consider the following:

$user = User::first();
protected function create(User $user); // OK

If that you load up relation the class of $user is no longer User by instead eloquent Model. So to prevent PHP Storm IDE errors you need to write:

use Illuminate\Database\Eloquent\Model;

$user = User::with('posts')->first();
protected function create(Model $user);

Obviously this not ideal as somebody could accidentally pass in any Eloquent model. PHP wise you can still type hint User model it works fine as it Model is sub class but the IDE gives you an error.

This has been bugging me a for while...

Thanks for any suggestion / ideas / fixed you may have!

Cheers, Juha

0 likes
1 reply
Sergiu17's avatar

hey, extra line, but solves the issue

/** @var User $user */
$user = User::with('posts')->first();

Please or to participate in this conversation.