Skip Unnecessary Eloquent Queries with withExists()
Imagine you're displaying a list of blog posts with a bookmark icon. You need to know whether each post has bookmarks, but you don't need to retrieve the actual bookmark records.
Loading the complete relationship just to check its existence is unnecessary.
Laravel provides withExists() for this situation.
The Traditional Approach
$posts = Post::with('bookmarks')->get();
foreach ($posts as $post) {
$hasBookmarks = $post->bookmarks->isNotEmpty();
}
This loads the related bookmark records even though you only need a yes-or-no answer.
Use withExists()
$posts = Post::query()
->withExists('bookmarks')
->get();
foreach ($posts as $post) {
if ($post->bookmarks_exists) {
// The post has bookmarks.
}
}
Laravel adds a bookmarks_exists boolean attribute to each post.
The related bookmark models aren't loaded into memory.
Check a Specific Relationship Condition
You can also check whether a post has any approved comments:
$posts = Post::query()
->withExists([
'comments as has_approved_comments' => function ($query) {
$query->where('approved', true);
},
])
->get();
Now each post has a has_approved_comments attribute that indicates whether an approved comment exists.
When Should You Use It?
Use withExists() when:
- Displaying status indicators in lists
- Checking whether products have reviews
- Determining whether posts have comments
- Checking whether users have related records
- You need relationship existence rather than relationship data