Back to Course |
Laravel 11 Eloquent: Expert Level

Methods to Query Relationship Data

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 has('projects') to the Eloquent query.

$users = User::has('projects')->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 />';
}

As a result, we can see that users without projects aren't being shown.

Also, has() can have filters. For example, we can show users who have more than one project.

$users = User::has('projects', '>', 1)->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 />';
}


whereHas()

Next, we have whereHas(), where we can provide some conditions in the callback function. For example, a project must have some keyword in the title.

$users = User::whereHas('projects', function (Builder $query) {
$query->where('title', 'LIKE', '%as%');
})
->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 />';
}

Alternatively, instead of whereHas() you can use the whereRelation().

$users = User::whereRelation('projects', 'title', 'LIKE', '%as%')->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 />';
}

Until now, we checked the existence of the relationship. However, you can also check the absence of the relationship with methods like doestHave() and whereDoesntHave().

There are more useful methods for querying relationships in a more readable way. You should check the official documentation.