Larastan: False negative on BelongsTo::associate()

Created on 3 Aug 2020  路  2Comments  路  Source: nunomaduro/larastan

  • Larastan Version: 0.6.2
  • --level used: 5

Description

PHPStan 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

Laravel code where the issue was found


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.

bug false positive

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 child in the relation clasess. I'll take a look into this :+1:

All 2 comments

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:

Was this page helpful?
0 / 5 - 0 ratings