Reputation: 262
I hope you get my point on my title hehe. Here's what I want to achieve.
I have User model that have relationship from Roles and Permissions. Here's the code:
class User extends Model {
....
public function roles() {
return $this->belongsToMany('App\Models\Roles');
}
public function permissions() {
return $this->belongsToMany('App\Models\Permissions');
}
}
and that work's fine but I want to have another function like this
....
public function permissions_by_roles() {
}
....
Because each user has individual permissions and permissions that is being inherited from roles. I want to get the list of user's permissions depending on user's roles. How can I achieve this? Here's my tables:
users roles permissions role_user - contains all roles of each user(ex. admin, super admin, user) permission_user - contains all permissions of each user (ex. edit, delete) permission_role - contains all permissions for each roles.
I hope anyone can help me. Thank you in advance! :)
Upvotes: 0
Views: 444
Reputation: 40653
You can use the hasManyThrough
relationship in combination with a merging where necessary:
class User extends Model {
....
public function roles() {
return $this->belongsToMany('App\Models\Roles');
}
public function permissions() {
return $this->belongsToMany('App\Models\Permissions');
}
public function inheritedPermissions() {
return $this->hasManyThrough('App\Models\Permissions', 'App\Models\Roles');
}
}
Then if you want all user permissions you can do:
$user = User::with(["permissions", "inheritedPermissions"])->where("id", $id)->first();
All permissions will be:
$allPermissions = $user->permissions->merge($user->inheritedPermissions)->unique("id");
Upvotes: 2