Courses

Laravel 11 Eloquent: Expert Level

HasManyThrough: 2-Level Deep hasMany

Summary of this lesson:
- Understanding HasManyThrough relationships
- Implementing multi-level relationships
- Managing deep relationship queries
- Optimizing nested relationship access

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 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