Laravel 8 Multiple Where Clause Example

  520 views   7 months ago Laravel

Laravel provides simple eloquent and query builder methods to query into database. The where() method is the basic clause to query into database. We almost need where clause in every query.

In this throughout tutorial, you will learn how to use multiple where condition into Laravel eloquent and query builder. You can use multiple where condition to filter multiple columns into database.

First let's see Laravel where() clause syntax:

->where('column_name', 'operator', 'value')

If you want to use where clause on multiple columns, you can constrains them as below:

...
->where('column_name', 'operator', 'value')
->where('another_column', 'operator', 'value')
...

Or you can pass array of conditions into where clause.

...
->where([
    ['column_name', 'operator', 'value'],
    ['another_column', 'operator', 'value']
])
...

The above both query creates same MySQL query:

SELECT * FROM `table_name` WHERE column_name = value AND another_column = value

Now let's see the query by example:

Example 1:

/**
 * Return users
 *
 * @return void
 */
public function index()
{
    $users = User::select('*')
        ->where('is_active', '=', 1)
        ->where('is_delete', '=', 0)
        ->get();
   
    dd($users);
}

Example 2:

You may omit the operator parameter if you want to pass (=) equal operator into where() condition.

/**
 * Return users
 *
 * @return void
 */
public function index()
{
    $users = User::select('*')
        ->where('is_active', 1)
        ->where('is_delete', 0)
        ->get();
   
    dd($users);
}

Example 3:

Using array of conditions into where condition.

/**
 * Return users
 *
 * @return void
 */
public function index()
{
    $users = User::select('*')
        ->where([
            ['is_active', '=', 1],
            ['age', '>', 18]
        ])
        ->get();
   
    dd($users);
}

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]