Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

False negative on BelongsTo::associate() #631

Closed
sebdesign opened this issue Aug 3, 2020 · 2 comments · Fixed by #633
Closed

False negative on BelongsTo::associate() #631

sebdesign opened this issue Aug 3, 2020 · 2 comments · Fixed by #633
Assignees
Labels
bug Something isn't working false positive

Comments

@sebdesign
Copy link
Contributor

sebdesign commented Aug 3, 2020

  • 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.

@canvural
Copy link
Collaborator

canvural commented Aug 3, 2020

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 👍

@canvural
Copy link
Collaborator

canvural commented Aug 6, 2020

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 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working false positive
Projects
None yet
2 participants