0
votes

I'm implementing a simple user role and permissions model in Laravel, but I'm not sure if the Eloquent relationship I need exists. I want to return a relationship of User's permissions, but that is via the Role model. A user only has one Role via role_id, but a Role has many Permissions.

Users belongsTo => Role hasMany => Permissions

I want an Eloquent relationship method of User->permissions() but hasManyThrough is not the right relationship structure.

Any ideas?

2

2 Answers

0
votes

like this.

User

public function permissions()
{
    return $this->role->permissions;
}
0
votes

You can use a HasManyThrough relationship:

class User extends Model
{
    public function permissions()
    {
        return $this->hasManyThrough(
            Permission::class, Role::class, 'id', null, 'role_id'
        );
    }
}