Gabrielle-M
Gabrielle-M

Reputation: 1077

Filtering pivot table data using intermediate relationship in Laravel eloquent

I'm working on Access Control Level (ACL) in laravel. here is, two pivot table one is role_user which is represent the each users roles and another one is permission_role which is represent the each roles permissions. now I want to get the permission_role pivot table data from Usermodel.

my code samples.

In User Model

public function roles()
{
    return $this->belongsToMany(Role::class);
}

In Role Model

public function users()
{
    return $this->belongsToMany(User::class);
}

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

public function roles()
{
    return $this->belongsToMany(Role::class);
}

I'm try this way:-

$user->roles->with('permissions')->get();

it shows BadMethodException.

How could i solve this issue and get the desire output.

Upvotes: 2

Views: 267

Answers (1)

Rwd
Rwd

Reputation: 35180

If you want to eager load nested relationships you can do by using the dot separated syntax e.g.:

User::with('roles.permissions')->find($id);

If the User model has already been instantiated then you can use the load() method instead (lazy eager loading):

$user->load('roles.permissions');

Eager Loading Documentation

Upvotes: 1

Related Questions