Skip to main content

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? (36 h 00 min)

You also get:

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

Already a member? Login here

Adrian leong avatar

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.

Modestas avatar

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

Adrian leong avatar

hello Modestas,

possible to have a simple show of code?

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

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.