0

I have a many to many Laravel Relationship Many Users have Many Roles

I know that I can do User::find(1)->roles()->get() to get all roles with an ID of 1 for a User but this requires me to know the ID of the role as oppossed to just its names

What sort of eloquent query could I put in my user Repository to do something like

public function getAllUsersWithRole($roleType){

  //Query goes here

}

Where $roleType is the name of the Role. So I need to look up the ID of the role based on hte name and then return users that have that role ID in the pivot table

Kevin Bradshaw
  • 6,327
  • 13
  • 55
  • 78
  • You are overcomplicating things for sure. You have the role, then simply do `$role->users;` to get all the users with this role. – Jarek Tkaczyk Sep 29 '14 at 18:19
  • I dont have the role. I just have the names of the roles and I want to count how many users have those roles. – Kevin Bradshaw Sep 29 '14 at 18:31
  • Then create a pseudo-relation for the count so you can eager load it - like `tags` here: http://stackoverflow.com/questions/25662854/laravel-many-to-many-loading-related-models-with-count#25665268 – Jarek Tkaczyk Sep 29 '14 at 18:34

3 Answers3

3

does this look like what you want:

public function getAllUsersWithRole($roleType){

  $role= Role::where('name', $roleType)->first();
  $users= $role->users;

  return $users;

}
Kholy
  • 441
  • 3
  • 10
0

If you have correct relation definitions in your Eloquent models you should be able to get the users by the role name this way:

$roleType = 'YourRoleName';
$users = Role::whereType($roleType)->first()->users;
MaGnetas
  • 4,918
  • 4
  • 32
  • 52
-1

Grab the users, then get the roles for all the users.

public function getAllUsersWithRole($roleType){

  $users = User::where('role_type', '=', $roleType)->get();
  $roles = $users->roles()->get();

  return $roles;

}
Jeremy Gehrs
  • 413
  • 6
  • 17
  • Would this work? Its a Many to Many relationship, so there is no 'role_type' field in User. The relationships are stored in a pivot table – Kevin Bradshaw Sep 29 '14 at 21:24
  • It would not then. You could either query the pivot table directly in that case, or if there aren't many users, retrieve them all and filter the list manually. – Jeremy Gehrs Sep 30 '14 at 01:02
  • It wouldn't work even if there was a `role_type` field on the users table. `$users->roles()` is wrong. – Jarek Tkaczyk Sep 30 '14 at 07:04