Laravel 9 Subquery In Where Condition

Websolutionstuff | Oct-11-2022 | Categories : Laravel MySQL

In this article, we will see the laravel 9 subquery in where condition. You can learn how to create subquery in laravel 9. Sometimes you may need to construct a "where" clause that compares the results of a subquery to a given value. You may accomplish this by passing a closure and a value to the where method.

We will see a subquery with the select() function in laravel 9. You can also use subquery with join query. And also, you can write a subquery with the selectraw() function in laravel 9.

So, let's see the laravel 9 subquery in where clause.

Example 1:

 In this example, we will retrieve all user's data with a given membership type.

use App\Models\User;
 
$users = User::where(function ($query) {
    $query->select('type')
        ->from('membership')
        ->whereColumn('membership.user_id', 'users.id')
        ->orderByDesc('membership.start_date')
        ->limit(1);
}, 'Basic')->get();

 

Example 2:

In this example, we will compare the column to the subquery using the operator in the where condition and retrieve all records. The following query will retrieve all income records where the amount is less than average.

use App\Models\Income;
 
$incomes = Income::where('amount', '<', function ($query) {
    $query->selectRaw('avg(i.amount)')->from('incomes as i');
})->get();

 


You might also like:

Recommended Post
Featured Post
Laravel 9 Livewire Toastr Notification
Laravel 9 Livewire Toastr Noti...

In this article, we will see laravel 9 livewire toastr notification. Here, we will learn how to create toastr notif...

Read More

Nov-28-2022

Laravel 11 Integrate Authorize.net Payment Gateway
Laravel 11 Integrate Authorize...

Hello, laravel web developers! In this article, we'll see how to integrate authorize.net payment gateway in laravel...

Read More

Sep-02-2024

How to Install and Configure Debugbar in Laravel 11
How to Install and Configure D...

Hello, laravel web developers! In this article, we'll see how to install and configure the debugbar in laravel...

Read More

Aug-02-2024

Laravel 9 Image Upload Example
Laravel 9 Image Upload Example

In this tutorial, I will explain the laravel 9 image upload example. image or file upload is the most common task in web...

Read More

Feb-28-2022