Check if a role has specific permission

Viewed 31

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

1 Answers

Use relationships.

User:

public function role() 
{
    return $this->belongsTo(Role::class);
}

Role:

public function permissions() 
{
    return $this->belongsToMany(Permission::class);
}

Checking if user has permission, something like this:

// $hasPermission will be true or false
$hasPermission = Auth::user()->role->permissions->contains('view-posts');

You may also want to add role and role.permissions to your user model $with property if this logic will be used inside of loops etc.

Related