Need to use withWhereHas in BelongsToMany Relationship

56 Views Asked by At

I have belongsToMany relationship.

Projects
- id
- name

Users
- id
- name

project_user
- project_id
- user_id
public function users(): BelongsToMany
{
    return $this->belongsToMany(User::class)->withWhereHas('roles', function ($query) {
        return $query->whereIn('name', ['Admin', 'Writer']);
    });
}

Now, need to add withWhereHas condition in relationship.

Any suggestion?

1

There are 1 best solutions below

0
Hesan Naveed On

I am not sure if there's a new method in Laravel 10. withWhereHas.

Project Model:

public function users(): BelongsToMany
{
    return $this->belongsToMany(User::class)->whereHas('roles', function ($query) {
        return $query->whereIn('name', ['Admin', 'Writer']);
    })->with('roles');
}