Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Relationship Packages

Premium
2:24

Now, let's take a look at a few packages related to Eloquent relationships.


Jonas Staudenmeir: Eloquent HasManyDeep

Another package I would like to demonstrate is from Jonas Staudenmeir and is called eloquent-has-many-deep for has many with unlimited levels.

In this example, I have such a structure: Country -> has many -> User -> has many -> Project -> has many -> Transaction. The goal is to calculate each country's SUM of transactions amount columns.

After installing the package via composer, we must add the Staudenmeir\EloquentHasManyDeep\HasRelationships trait to the Model. In this example, it is the Country Model.

use Illuminate\Database\Eloquent\Relations\HasMany;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;
 
class Country extends Model
{
use HasRelationships;
 
public function users(): HasMany
{
return $this->hasMany(User::class);
}
}

Now, we can use the hasManyDeep relationship to get transactions. This is similar to the has many through relationship but one deeper lever.

use Staudenmeir\EloquentHasManyDeep\HasManyDeep;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;
 
class Country extends Model
{
use HasRelationships;
 
public function users(): HasMany
{
return $this->hasMany(User::class);
}
 
public function transactions(): HasManyDeep
{
return $this->hasManyDeep(Transaction::class,
[User::class, Project::class],
['country_id', 'owner_id', 'project_id']
);
}
}

In the hasManyDeep() method, you first define...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

BD
Bless Darah ✓ Link copied!

I find the list of packages here particularly useful for me. Especially the Parental (which I would just extend the table using another class) and the Cascade soft delete package.