HasManyThrough Relationships With Unlimited Levels


April 2nd, 2021

HasManyThrough Relationships With Unlimited Levels

The eloquent-has-many-deep package by Jonas Staudenmeir allows Eloquent HasManyThrough relationships with unlimited levels. It supports many-to-many and polymorphic relationships and all their possible combinations.

The package's readme illustrates various types of relationships that this package supports:

  • HasMany
  • ManyToMany
  • MorphMany
  • MorphToMany
  • MorphedByMany
  • BelongsTo

Here's an example from the readme of a HasMany relationship for a complex relationship:

-> has many
-> has many
-> has many
class Country extends Model
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function comments()
return $this->hasManyDeep('App\Comment', ['App\User', 'App\Post']);
// Access country comments

In the above example, the package uses Eloquent conventions keys, and the package allows you to specify custom keys for local and foreign keys.

Learn More

You can learn more about this package, get full installation instructions, and view the source code on GitHub. Check out the package's readme for in-depth usage of this package.

Click here to see even more Laravel Eloquent Packages and Tutorials.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.