Courses

Laravel 11 Eloquent: Expert Level

Relationship Packages

Summary of this lesson:
- Using HasManyDeep package
- Implementing Parental package
- Managing cascade soft deletes
- Understanding relationship package benefits

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 28 lessons of this course? (71 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord