If I'm having 2 tables with n:n relationship, users and roles. How can I get all roles for all users in laravel.
example:
John | Jack |
---|---|
role1 | role1 |
role2 | role3 |
CodePudding user response:
By foreach
foreach($users as $user) {
$user->roles;
}
CodePudding user response:
Don't forget to use with() to reduce N 1 problem. do simple foreach and fetch the name.
$users = User::with('roles')->get();
foreach($users as $user) {
$user->roles->name;
}