Arne
Arne

Reputation: 79

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). Now i want to get all the permissions from a certain user.

I'm using Laravel 5.8 and 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.

Upvotes: 0

Views: 1144

Answers (2)

Mikhail Solovyan
Mikhail Solovyan

Reputation: 46

You can add to method rights() to User model:

public function rights()
    {
        return $this->hasManyThrough(Role::class, Right::class);
    }

and then use $user->rights();


Additional info: Laravel has't Thought for manyToMany.

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]);
    }
}

Upvotes: 0

Lijesh Shakya
Lijesh Shakya

Reputation: 2542

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;
}

Upvotes: 1

Related Questions