Mark Topper
Mark Topper

Reputation: 664

Where Clause in Relationship

I need to create a where clause in the User model to get only users from a special Group.

I have the table group_user which is a many-to-many table.

I need to get out all users that have group Admin.

How can this be filtered using the Eloquent Relationship methods?

Upvotes: 0

Views: 91

Answers (1)

Matt Burrow
Matt Burrow

Reputation: 11057

You can use the whereHas method to query your relation like so;

User::whereHas('group', function($query){
    $query->where('name', 'Admin');
})->get();

This will return only the users that have a group related to them, with the name of Admin.

Please Note: This assumes you have already set up your relation to the group within your User model, with the relation name of group.

To set up the relationship use the following within your User model;

public function group(){
    return $this->belongsToMany('Group', 'group_user', 'user_id', 'group_id');
}

For more go to here.

Upvotes: 1

Related Questions