Laravel 8.x withExists Method to Eloquent Queries Example - TechvBlogs

Laravel 8.x withExists Method to Eloquent Queries Example

In this blog, We will learn how we can use this withExists method to our eloquent query.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

2 years ago

TechvBlogs - Google News

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.

Read Also:  Laravel One of Many Eloquent Relationship Example

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.

Comments (0)

Comment


Note: All Input Fields are required.