In real life the code above returns the following exception:
Call to undefined method Illuminate\Database\Query\Builder::permissions
It is saying there is no method called called permissions in the user object. Can you show us what is in your user class?
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.
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!
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']);
}
}
If you understand many to many relationships then you can go to https://appdividend.com/2018/05/17/laravel-many-to-many-relationship-example/
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community