[英]How to get permissions from a user that has multiple roles in Laravel?
I'm building a new laravel application, where a user can have multiple roles and these roles have multiple rights (permissions) . 我正在构建一个新的laravel应用程序,其中用户可以具有多个角色,并且这些角色具有多个权限(权限) 。 Now i want to get all the permissions from a certain user.
现在,我想从某个用户那里获得所有权限。
I'm using Laravel 5.8 and Eloquent. 我正在使用Laravel 5.8和Eloquent。 I can get the roles from a user an permissions from a role, but not the permissions from a user.
我可以从用户那里获得角色,从角色那里获得权限,但不能从用户那里获得权限。
dd(Auth::user()->roles->rights);
Model user: 模型用户:
public function roles()
{
return $this->belongsToMany(Role::class);
}
Model role: 模特角色:
public function users()
{
return $this->belongsToMany(User::class);
}
public function rights()
{
return $this->belongsToMany(Right::class);
}
Model right 模特儿权利
public function roles()
{
return $this->belongsToMany(Role::class);
}
I'm expect to get all permissions for one user past trough by the roles he has. 我希望通过一名用户来获得一个过去的用户的所有权限。
Since One User can have many roles and one role can have many rights, you will need to loop through each roles 由于一个用户可以具有多个角色,而一个角色可以具有许多权限,因此您将需要遍历每个角色
//Retrieving rights associated with the user
public function retrieveRightsAssociatedWithUser($user){
$rightsAssociatedWithUser = [];
foreach($user->roles as $role){
$rightsAssociatedWithUser[] = $role->rights;
}
return $rightsAssociatedWithUser;
}
You can add to method rights() to User model: 您可以向用户模型添加方法right():
public function rights()
{
return $this->hasManyThrough(Role::class, Right::class);
}
and then use $user->rights(); 然后使用$ user-> rights();
Additional info: Laravel has't Thought for manyToMany. 附加信息:Laravel还没有为多对多的想法。
You can install pakage 您可以安装包装
composer require staudenmeir/eloquent-has-many-deep
and use this: 并使用此:
class User extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function rights()
{
return $this->hasManyDeep(Right::class, ['role_user', Role::class]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.