Home > front end >  How to groupBy many to many relationships in Laravel
How to groupBy many to many relationships in Laravel

Time:01-02

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’);

CodePudding user response:

Use wildcard * to skip an array:

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