Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 2 years ago.
0

In real life the code above returns the following exception:

Call to undefined method Illuminate\Database\Query\Builder::permissions

Last updated 2 years ago.
0

It is saying there is no method called called permissions in the user object. Can you show us what is in your user class?

Last updated 2 years ago.
0

That is a Has-Many-Through relationship.
Otherways, you can use your current implementation like this

$user = User::find($id);
$roles = $user->roles()->get();
foreach($roles->permissions()->get() as $permission){
//do stuff with $permission
}

This will result in multiple queries. Use eager loading to make it better.

Last updated 2 years ago.
0

I don't think the "has-many-through" works for relationships requiring an intermediary/pivot table. I'm just going to do the longhand way for now. Thanks for everybody's help!

Last updated 2 years ago.
0
$user->roles()->with('permissions');

maybe?

Last updated 2 years ago.
0

I created a HasManyThrough relationship with support for BelongsToMany: Repository on GitHub

After the installation, you can use it like this:

class User extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function permissions() {
        return $this->hasManyDeep(Permission::class, ['role_user', Role::class, 'permission_role']);
    }
}
0

If you understand many to many relationships then you can go to https://appdividend.com/2018/05/17/laravel-many-to-many-relationship-example/

Last updated 5 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

james2037 james2037 Joined 15 Oct 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.