Norgul
Norgul

Reputation: 4783

Laravel where on relationship

I have a M-M relationship on User and Roles. Also, one User belongs to Clinic. I would like to filter out all users belonging to one role, which have specific clinic_id. I am trying with this one but it doesn't work:

$user = Role::where('name', 'admin')->first()
                 ->users->where('clinic_id', Auth::user()->clinic_id)->get(); 

I am getting an error on this one

Type error: Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in 

Relationship is defined fine, and if I exclued the with() I get back all users who are admins.

Upvotes: 1

Views: 39

Answers (1)

Sandeesh
Sandeesh

Reputation: 11906

Change roles based on your role relationship name.

$clinic_id = auth()->user()->clinic_id;

$users = User::whereHas('roles', function ($query) {
    $query->where('name', 'admin');
})->where('clinic_id', $clinic_id)->get();

Upvotes: 1

Related Questions