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
How To Use Array In React JS
How To Use Array In React JS

In this article, we will see how to use an array in React JS. We can use the JavaScript standard Array functio...

Read More

Aug-12-2022

How To Send Email With Attachment In Laravel 9
How To Send Email With Attachm...

In this article, we will see how to send email with attachments in laravel 9. As we all know mail functionalities are co...

Read More

Mar-16-2022

Laravel 8 Datatables Keeping Selected Page Number
Laravel 8 Datatables Keeping S...

In this tutorial we will see laravel 8 datatables keeping selected page number after callback. In datatable page nu...

Read More

Dec-03-2021

Laravel tips: DB Models and Eloquent
Laravel tips: DB Models and El...

In the realm of web development, an efficient and robust data handling mechanism is paramount. Laravel, a PHP web applic...

Read More

Oct-11-2023