Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

anon12822's avatar

Users Permissions (Role-based Permissions)

I'm trying to create from scratch a role-based permission layer as I've come back from a hiatus recently and it will help me with getting back into the swing of it.

I'm trying to do as much without looking at other packages as it'll will end up being the same if I do and I don't feel I'd learn as much.

Question

What the would be the best way to retrieve all permissions a user has through the roles they currently have?

I'd ideally like my interaction with my user model to end up like: $user->permissions

Database Setup

Schema Image

Eloquent Relations

I also have the following relations setup in my Eloquent models:

  • Users

    • belongsToMany(Role::class)
  • Roles

    • belongsToMany(User::class)
    • belongsToMany(Permission::class)
  • Permissions

    • belongsToMany(Role::class)

Any help would be appreciated!

0 likes
2 replies
Cinek's avatar
Cinek
Best Answer
Level 6

Try this in your User model:

public function getPermissionsAttribute(){
        return Permission::whereHas('roles.users',function ($query) {
            $query->where('id',$this->id);
        })->get();
    }

and

$permissions = $user->permissions;

Edit: 'roles' - your relation in Permission class 'users' - your relation to Users in Roles class

1 like
anon12822's avatar

That is exactly what I wanted! Thank you very much.

Please or to participate in this conversation.