Skip to main content

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

Read more here

Methods to Query Relationship Data

Premium
2:21

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

TL
Tibor Lakatos ✓ Link copied!

the end of article doestHave() is doesntHave(), pls fix

PK
Povilas Korop ✓ Link copied!

Wow, not sure why I noticed this comment only now. Fixed, thanks Tibor!