Introduction
Hello Developer, In this blog, I will teach you the relationship withExist Method in Queries. Some days ago, Taylor Otwell merged withExists method to Queries Relationships in Laravel 8.x.
In this blog, you can learn how to use the withExists Method in Your Eloquent Query. You can see the merged request from this link. Let's now see how to use this method:
$users = User::withExists('posts')->get();
//...
$isAuthor = $user->posts_exists;
The column name can also be aliased:
$users = User::withExists('posts as is_author')->get();
//...
$isAuthor = $user->is_author;
Relations can filter relations, and multiple relation existences can be fetched at the same time:
$users = User::withExists([
'posts as is_author',
'posts as is_tech_author' => function ($query) {
return $query->where('category', 'tech');
},
'comments',
])->get();
//...
$user->is_author;
$user->is_tech_author;
$user->comments_exists;
Thank you for reading this blog.
Top comments (4)
That's amazing, I didn't know about this feature. One question tho, how is it different from
?
has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.
It actually does a JOIN. So it can cut down on queries run.
This syntax will not work for some reasons :
the ->select() call needs to be before ->withExists call