2

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?

vrxj81
  • 41
  • 5

2 Answers2

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

Community
  • 1
  • 1
Max Stern
  • 180
  • 3
  • 8
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