DEV Community

loading...
Cover image for Laravel 8.x withExists Method to Eloquent Queries Example

Laravel 8.x withExists Method to Eloquent Queries Example

Suresh Ramani
Laravel & Vue.js Developer
Originally published at techvblogs.com ・1 min read

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Thank you for reading this blog.

Discussion (4)

Collapse
bdelespierre profile image
Benjamin Delespierre

That's amazing, I didn't know about this feature. One question tho, how is it different from

User::has('posts')->get();
Enter fullscreen mode Exit fullscreen mode

?

Collapse
sureshramani profile image
Suresh Ramani Author

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.

Collapse
skeemer profile image
Leo Lutz

It actually does a JOIN. So it can cut down on queries run.

Collapse
lk77 profile image
Mathias E.

This syntax will not work for some reasons :

User::withExists([
        'posts as is_author',
        'posts as is_tech_author' => function ($query) {
            return $query->where('category', 'tech');
        },
        'comments',
    ])->select([... some fields to select ...])->get();
Enter fullscreen mode Exit fullscreen mode

the ->select() call needs to be before ->withExists call