Skip to main content

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? (30 h 50 min)

You also get:

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

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.