Laravel 8.x withExists Method to Eloquent Queries Example

Hello artisan in this example i will explain withExists method to queries relationships in Laravel 8.x. Somedays ago taylorotwell merged withExists method to Queries Relationships in Laravel 8.x.

In this example you will learn how you can use this withExists method to your eloquent query. You can see the merged request from this link . Let's take a look to the below example:

$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 be filtered 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;

 

Read also: Laravel One of Many Eloquent Relationship Example

 

Hope it can help you.

 

author-image
Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js