EasyWay
EasyWay

Reputation: 365

Laravel Eloquent Model Relationship with Condition in Relationship

Hello Laravel Enthusiasts,

I have tables for Users, Roles and Roles_User

Role : id, role_name

Roles_User : id, role_id, user_id

in my Controller I have this

$users = User::all();
return view('admin.users.index', compact('users'));

How can I can display in my view all the users that has a role name with 'admin' or 'member'

Please help me build my Model and View.

Thank you

Upvotes: 0

Views: 205

Answers (1)

Kurt Friars
Kurt Friars

Reputation: 3764

Stack Overflow is not a coding service, you will need to build your view. Read here.

As For the query, its simple:

 $users = User::query()
              ->join('role_user', 'role_user.user_id', '=', 'users.id')
              ->join('roles', 'roles.id', '=', 'role_user.role_id')
              ->whereIn('roles.role_name', ['admin', 'member'])
              ->get();
 

If you have your relationships set up in your models, you can do the following:

$users = User::whereHas('roles', function ($query) {
             $query->whereIn('role_name', ['admin', 'member']);
         })->get();

Upvotes: 1

Related Questions