How to Create Multiple Where Clause Query Using Laravel Eloquent

How to Create Multiple Where Clause Query Using Laravel Eloquent

In Laravel Eloquent, you can chain multiple where clauses together to create a query with multiple conditions. Each where clause you append will be treated as an AND condition.

Here’s a basic example of how you can do this:

$users = User::where('age', '>=', 18)
          ->where('account_type', '=', 'premium')
          ->where('status', '=', 'active')
          ->get();

This would generate a SQL query similar to:

SELECT * FROM users 
WHERE age >= 18 
AND account_type = 'premium' 
AND status = 'active';

Laravel OrWhere

If you need to use an OR condition, you can use the “orWhere()” method.

$users = User::where('age', '<', 18)
         ->orWhere('account_type', '=', 'standard')
         ->get();

Laravel Where with Arrays

You can pass an array to the where method to specify multiple conditions.

$users = User::where([
           ['age', '>=', 18],
           ['account_type', '=', 'premium'],
           ['status', '=', 'active'],
         ])->get();

Laravel Nested Where Clauses

You can nest where clauses for more complex queries using closures.

$users = User::where('age', '>=', 18)
          ->where(function($query) {
             $query->where('account_type', '=', 'premium')
          ->orWhere('status', '=', 'inactive');
         })
    ->get();

Laravel WhereIn and WhereNotIn

To filter results based on whether a column’s value is within a set of values (or not within), you can use the whereIn and whereNotIn methods.

$users = User::whereIn('id', [1, 2, 3, 4])
           ->get();

Eloquent provides several other conditional methods like whereBetween, whereNotNull, whereDate, etc., for building specific conditions.

That’s it!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.