Have you defined a roles relationship in the User model?
laravel retrieve all users where value match pivot table
So im trying to make relationship between user roles and profiles everything works connected on creation but i don't know how to filter out when i want to list users by specific role or profile.
Here is a table structure that i have now. Each table corresponds to it's model, so table users have model User table roles have model Role and there is a pivot table role_user that connects users with roles.
This would be role table
+----+----------+---------------+
| id | name | Description |
+----+----------+---------------+
| 1 | admin | Administrator |
| 2 | client | Client |
| 3 | operator | Operator |
+----+----------+---------------+
This would be pivot table for user role
+----+---------+---------+
| id | user_id | role_id |
+----+---------+---------+
| 1 | 1 | 3 |
| 2 | 2 | 1 |
+----+---------+---------+
And this would be user table normally
+----+--------+-----------------+
| id | name | Email |
+----+--------+-----------------+
| 1 | Mario | [email protected] |
| 2 | Luighi | [email protected] |
+----+--------+-----------------+
So if i would list all account that is very simple, as i would just use
public function index(Request $request)
{
$users = User::get();
return view('users/index', compact('users'));
}
If i want to filter users by specific name or email i would just filter
$users = User::where('name', 'Mario')->get();
That would retrieve all users where matching name is mario.
Now something more complex is where i stumbled upon and i couldn't quite find answers on internet.
I want to retrieve all users where user role from pivot table matches role from role table.
Example would be
Retrieve All Users WHERE (pivot table) role_user EQUALS name OPERATOR from role table
That would return user Mario, as his user id is 1 and in pivot table that user_id matches role_id 3 which in roles table is role named OPERATOR.
@lonerunner if in you have a roles relation on user :
$users = App\User::whereHas('roles', function($query) {
$query->where('id', 3);
})
->get();
You get the idea.
Please or to participate in this conversation.