Reputation: 3117
I have five tables to setup relationship between 3 tables are: + users + roles + permissions
The relationship of users and roles are many to many
through pivot table is "user_role
"
The relationship of roles and permissions are also many to many
through pivot table is "role_permission
"
Now I want to display list users but I want bring their permissions on this list. How can I do that?
Name Email Role Permission
aaa [email protected] Moderator, Customer create-post, update-post, delete-post
Upvotes: 2
Views: 962
Reputation: 1769
I have recently done this scenario by doing this way
User Model
public function roles()
{
return $this->belongsToMany(Role::class,UserRole::class);
}
Role Model
public function permissions()
{
return $this->belongsToMany(Permission::class,RolePermission::class);
}
Now when you are getting all users you need to eager load your relationships
public function index()
{
$users = User::with('roles.permissions')->get();
OR
$users = User::with(['roles' => function($query){
$query->with('permissions');
}])->get();
return view('view_name',compact('users'));
}
Note: You can also use laravel collections to reformat your roles and permissions collections for not using multiple loops. But I think you get the idea
Upvotes: 2