I have 4 tables (users, permissions, roles, roles_permissions) with the following structure:
users
_______________________
| id | name | role_id |
|____|______|_________|
| 1 | John | 1 |
|____|______|_________|
roles
______________
| id | name |
|____|_______|
| 1 | admin |
|____|_______|
permissions
____________________
| id | permission |
|____|_____________|
| 1 | view-posts |
|____|_____________|
roles_permissions
________________________________
| id | permission_id | role_id |
|____|_______________|_________|
| 1 | 1 | 1 |
|____|_______________|_________|
I want to check if the current user has specific permission like view-posts. This is what I tried so far in Permission.php model:
public function checkPermission($permission){
$role = Auth()->user()->role_id;
$id = $this->select('permissions.id')->join('role_permissions as rp', 'rp.permission_id', 'permissions.id')->where('rp.role_id', $role)->where('permission', $permission)->get()->toArray();
return $id ? true : false;
}
So to check with this method I can run:
$permission = new permission();
$check = $permission->checkPermission('view-posts');
Is there a short/better way?
PS: Don't suggest using a permissions package as I want to use this custom method for a reason