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 Generate PDF and Send Email In Laravel 8
How To Generate PDF and Send E...

In this tutorial we will see how to generate pdf and send email in laravel 8. For generating PDF file we will use l...

Read More

Dec-20-2021

Introduction of Node.js Modules
Introduction of Node.js Module...

In this tutorial I will give you information about Introduction of Node.js Modules. Node.js modules provide a way t...

Read More

Sep-10-2021

Adding Bootstrap 5 To Angular 15: Step-by-Step Guide
Adding Bootstrap 5 To Angular...

Welcome to my comprehensive step-by-step guide on integrating Bootstrap 5 into Angular 15. As a developer, I understand...

Read More

Jun-12-2023

How to Install PHP PDO MySQL Extension in Ubuntu 22.04
How to Install PHP PDO MySQL E...

Hey there! If you're diving into PHP development on Ubuntu 22.04 and need to connect your applications to MySQL data...

Read More

Feb-28-2024