How to groupBy many to many relationships in Laravel

Viewed 234

I have this basic database model I would like to group all users by role name i.e. I want to list the users who are admins and the others in two collections.

Database model

enter image description here

I tried to do this but it only works for one to many relationships

User::with('roles’)->get()->groupBy(‘roles.name’);
1 Answers

Use wildcard * to skip an array:

User::with('roles')->get()->groupBy('roles.*.name');
Related