--level used: 5PHPStan reports the following error: Method App\Post::setAuthorAttribute() should return App\User but returns App\Post.
The associate method of the BelongsTo relation does not return the related model, but the child model: https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Eloquent/Relations/BelongsTo.php#L216
But Larastan assumes the opposite: https://github.com/nunomaduro/larastan/blob/master/stubs/BelongsTo.stub#L11
class Post extends Model
{
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
public function setAuthorAttribute(User $user): self
{
return $this->author()->associate($user);
}
}
I have no idea how Larastan or PHPstan works, otherwise I would send a PR for this issue.
Hi,
Thanks for the report! Yes, this looks like a wrong assumption in the stub file. Maybe additionally we need to keep track of the child in the relation clasess. I'll take a look into this :+1:
Fixed with #633
I could only find this situation (returning child model) in associate, dissociate, and getChild methods of BelongsTo relation. If you encounter this behavior in different relation methods, let me know :+1:
Most helpful comment
Hi,
Thanks for the report! Yes, this looks like a wrong assumption in the stub file. Maybe additionally we need to keep track of the
childin the relation clasess. I'll take a look into this :+1: