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:


/*
 Country
   -> has many
 User
   -> has many
 Post
   -> has many
 Comment
*/

class Country extends Model
{
    use StaudenmeirEloquentHasManyDeepHasRelationships;

    public function comments()
    {
        return $this->hasManyDeep('AppComment', ['AppUser', 'AppPost']);
    }
}

// Access country comments
$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.

To learn more about what ships with the Laravel framework, check out the Eloquent: Relationships documentation.