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 add Pagination in Laravel 11 Livewire
How to add Pagination in Larav...

Hello, laravel web developers! This article will show how to add pagination in laravel 11 Livewire. Here, we'll...

Read More

Jun-14-2024

How To Check Image Blur Or Not Using Python
How To Check Image Blur Or Not...

In this article, we will see how to check image blur or not using python. For blur image check we are using the OpenCV p...

Read More

May-13-2022

How To Validate International Phone Number Using jQuery
How To Validate International...

In this article, we will see how to validate international phone numbers using jquery. Here, we will learn about mo...

Read More

May-12-2023

How to Force Redirect Http to Https in Laravel
How to Force Redirect Http to...

In this small artical we will see how to force redirect http to https in laravel, Here i will show you two method in&nbs...

Read More

Aug-11-2021