Nick Bedford
Nick Bedford

Reputation: 4445

Eloquent hasManyThrough a belongsTo relationship?

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?

Upvotes: 0

Views: 246

Answers (3)

Natvarsinh Parmar - bapu
Natvarsinh Parmar - bapu

Reputation: 1138

I assume you have model with name User.php Role.php Permission.php

then relationship define as per below

In User.php

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

In Role.php

public function permissions()
{
    return $this->hasMany(Permission::class, 'role_id');
}

Now use this relationship

public function show($id)
{
    $user = User::select('id', 'name', 'email', 'role_id')
        ->with([
            'role.permissions'
        ])
        ->find($id);

    $permissions = $user->role->permissions;

    dd($permissions); //here is your permission list
}

Upvotes: 0

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25936

You can use a HasManyThrough relationship:

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

Upvotes: 0

lightwill
lightwill

Reputation: 1

like this.

User

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

Upvotes: 0

Related Questions