Skip to main content

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

Read more here

HasManyThrough: 2-Level Deep hasMany

Premium
1:38

I will show you another type of relationship: has many through. It's just a fancy word for defining two-level-deep has-many relationships.


Imagine a scenario where you have a user with many projects, and then you have projects with many tasks.

And you want to show the users their own tasks, bypassing the projects. But to get to the tasks, you still need to load the projects, right?

So, for each user, you perform a loop through projects and then a loop through tasks. Then, you will show a description of the task.

$users = User::with('projects.tasks')->get();
 
foreach ($users as $user) {
print '<div><strong>' . $user->id . ': ' . $user->name . '</strong></div>';
 
foreach ($user->projects as $project) {
foreach ($project->tasks as $task) {
print $task->description .'... ';
}
}
 
print '<hr />';
}

But there's a shorter way. Using the model, we can define a Has Many Through relation. The hasManyThrough() first accepts the class of which records we want to get, and the second parameter is the intermediate class. So, we want to...

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

AL
Adrian leong ✓ Link copied!

possible to add scope to the hasManyThrough relationship?

For example,

i would like to return the pending or done tasks only in a project.

or only return active projects' tasks only.

M
Modestas ✓ Link copied!

Yep! Any relationship can have scopes added to it (or even default values) :)

AL
Adrian leong ✓ Link copied!

hello Modestas,

possible to have a simple show of code?

I could not imagine how it would look like...