HasManyThrough with polymorphic and many-to-many relations HasManyThrough with polymorphic and many-to-many relations laravel laravel

HasManyThrough with polymorphic and many-to-many relations


Try something like this:

public function users()    {        $Foo = static::with(['bars', 'bars.products', 'bars.product.users'])->get();        return collect(array_flatten(array_pluck($Foo, 'bars.*.product.users')));    }

This should work for you (code has been tested, but not against the exact same structure as your setup). The first line will return all the users deeply nested through the relationships. The second line will pull out the users, flatten them into an array, then transform the array into a collection.


I created a HasManyThrough relationship for cases like this: Repository on GitHub

After the installation, you can use it like this:

class Foo extends Model {    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;    public function users() {        return $this->hasManyDeep(            User::class,            [Bar::class, Product::class, 'products_users'],            [null, ['extended_type', 'extended_id']]        );    }}