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.
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();
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:
In this article, we will see laravel 9 QR code generator example. As per the current trend, many websites and appli...
Mar-25-2022
In this article, we will see how to create a parallax scrolling effect using jquery. Parallax scrolling is a websit...
May-04-2022
Hey folks, are you ready to make your Laravel Vue.js application even more user-friendly by implementing validation erro...
Mar-08-2024
In this example we will see PHP access modifiers example. In PHP default access modifier is public. PHP provide differen...
Sep-06-2021