Ahmed Ibrahim Meraneh
Ahmed Ibrahim Meraneh

Reputation: 25

How to groupBy many to many relationships in Laravel

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

Upvotes: 2

Views: 1196

Answers (1)

Wilson
Wilson

Reputation: 825

Use wildcard * to skip an array:

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

Upvotes: 3

Related Questions