I'm making my own role based access control implementation and need some help on a relationship question.
I have a User, Group and a Permission model, there's a pivot table between User / Group and between Group / Permission. How would I most efficiently retrieve the Permission model through the User model?
Thank you.
Edit:
Relationship is as follows;
User belongsToMany Group Group belongsToMany User
Group belongsToMany Permission Permission belongsToMany Group
According to your Pivot Tables
relations are as follows:
Group <-> User
has many-to-many
Group <-> Permission
has many-to-many
How would I most efficiently retrieve the Permission model through the User model
Since there is no direct relationship between User
and Permission
model but you can get all the permissions through Group
model:
$user = User::with('groups.permissions')->find(1);
This will give you the User
model with all Group
models and nested Permission
models so to get permissions you may try:
// Get a collection
$permissionsOfFirstGroup = $user->groups->first()->permissions;
// Get a collection
$permissionsOfSecondGroup = $user->groups->get(1)->permissions;
To get all permissions from all the groups you may try this:
$permissions = $user->groups->fetch('permissions');
This will return you a Illuminate\Database\Eloquent\Collection
object (A Collection of Permission
models).
There are other ways (Using joins) but depends on your need how you do it.