Courses

Laravel 11 Eloquent: Expert Level

Methods to Query Relationship Data

Summary of this lesson:
- Using has() and whereHas() methods
- Implementing relationship existence queries
- Understanding relationship constraints
- Managing nested relationship conditions

Now, I will show you a few tricks for querying the relationships.


has()

For example, you have a user with many projects and want to query only those with projects. For that, eloquent has a has() method.

Before adding the has() the code to fetch and show the result:

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

And the result. As we can see, users with IDs two, five, and eight don't have projects.

Now, let's add...

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