I am building an app with a many-to-many between users and roles and a many-to-many between roles and permissions. I would like to get the permissions of a user with the hasManyThrough, but it doesn't work. This relation expects a user_id in the roles table, but as they are many to many, there is none of course. Anyone who has a fix?
Asked
Active
Viewed 1,022 times
2 Answers
0
hasmanythrough on a many-to-many relationship is not possible.
This has been answered in more detail in another thread: HasManyThrough with one-to-many relationship
And you can also refer to: http://laravel-tricks.com/tricks/i-has-many-through-relation-laravel-the-missed-shortcut
0
There is a Laravel 5.5 composer package that can perform multi-level relationships (deep)
Package: https://github.com/staudenmeir/eloquent-has-many-deep
Example:
User
→ belongs to many → Role
→ belongs to many → Permission
class User extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function permissions()
{
return $this->hasManyDeep(
'App\Permission',
['role_user', 'App\Role', 'permission_role'], // Pivot tables/models starting from the Parent, which is the User
);
}
}
Example if foreign keys need to be defined:
https://github.com/staudenmeir/eloquent-has-many-deep/issues/7#issuecomment-431477943

Nickson Yap
- 1,146
- 15
- 23