How to use Laravel multiple Where Clause Query Using Eloquent?

Laravel multiple Where Clause

Here are multiple ways to use the laravel multiple where clause query using eloquents.

Model::where('column_1','=','value_1')
       ->where('column_2 ','=','value_2')
       ->get();

OR

Model::where(['column_1' => 'value_1',
              'column_2' => 'value_2'])->get();

The whereColumnmethod can be passed an array of multiple conditions.

$users = DB::table('users')
                ->whereColumn([
                    ['first_name', '=', 'last_name'],
                    ['updated_at', '>', 'created_at'],
                ])->get();

Sometimes you may need to group several “where” clauses within parentheses in order to achieve your query’s desired logical grouping.

$users = User::where('name', '=', 'John')
           ->where(function ($query) {
               $query->where('votes', '>', 100)
                     ->orWhere('title', '=', 'Admin');
           })
           ->get();

You can use subqueries in anonymous function like this:

$users = User::where('active', 1)
       ->where(function($query) {
            return $query
                ->where('approved', '1')
                ->orWhere('subscribed', 1);
        })
        ->get();

You can get more details about this topic from here.
To get to know more about the Laravel, you can check these articles too.

Please follow and like us:

Related Posts

Leave a Reply

Share