whereHas Bug? BelongsToMany

Posted 2 years ago by tiagotavares

Hello,

I just can't understand why, I need to create an empty Object, instead of using $this.

The first example works, but the second doesn't... The second returns true because it ignores the current object id

class Card extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class, 'card_user', 'card_id', 'user_id');
    }

    public function isCompleted($user)
    {
        return (new static)->where('id', $this->id) // No idea why i need to create a new instance.... and cant use $this
            ->whereHas('users', function ($query) use ($user) {
            $query->where('user_id', $user->id);
        })->exists();
    }
}
    public function isCompleted($user)
    {
        return $this->whereHas('users', function ($query) use ($user) {
            $query->where('user_id', $user->id);
        })->exists();
    }

Thanks in advance

Conclusion:

@AkiyamaSmart I didn't understand what you wrote at first (missing commas ;) ), but now it all makes sense. where and whereHas are supposed to filter eloquent models, if I already have the filtered model to 1 record/eloquentItem, there is no need to filter it.

Please sign in or create an account to participate in this conversation.