I am building the middleware for permissions. Permissions are based on either user action types and/or module/element type (ie delete button).
The model ActionPermission
(table action_permission
) has all the permission types while table users__action_permission
is the pivot for User
& ActionPermission
with all users and their permission IDs.
User
has a permissions()
method that gets all the permissions for user
public function permissions()
{
return $this->hasMany('App\ActionPermission');
}
checkUserPermissions
(middleware) public function handle($request, Closure $next)
{
$response = $next($request);
$userId = Auth::id();
$userPermissions = User::findOrFail($userId)->permissions()->get();
dd($userPermissions);
}
Since permissions()
is looking for user_id
key, and ActionPermission
model (table action_permission
) does not have the relevant user_id
key, I need the table users__action_permission
which holds he user_id
.
My question is if Laravel has a way for User::permissions()
to access users__action_permission
table, or do I need to build a model for that?
You do not need a model for the pivot table.
in User model add
public function ActionPermissions() {
return $this->belongsToMany('App\User', 'users_action_permission');
}
in Action Permission model add
public function Users() {
return $this->belongsToMany('App\ActionPermission', 'users_action_permission');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.