Posts Learn Components new Snippets new Categories Tags About
/

How to Query Laravel Eloquent With Multiple WHERE Conditions?

Learn how to query Laravel Eloquent with multiple WHERE conditions to construct a more complex condition in an elegant manner.

Created on Sep 27, 2021

57 views

In this short snippet, you will learn how to create multiple where clause queries using Laravel Eloquent to construct a more complex condition the easy way so let's get started.

Method 1: Laravel Basic Query Multiple WHERE Condition


To basic way to query with multiple where clauses are to chain the "where" method continuously and passing in the condition as follows.
<?php

$results = Post::query()
    ->where('post_status', '=', 1)
    ->where('user_id', '=', 1)
    ->where('published_code', '=', 1)
    ->get();

Method 2: Laravel Query Multiple WHERE Condition With Array


Another approach is to pass in an associative array that contains the different types of conditions.
<?php

$results = Post::query()
    ->where([
        ['post_status', '=', 1],
        ['user_id', '<>', 1]
    ])
    ->get();
Or if you want to check for "greater" and "lower" operators then you can use the "whereColumn" like below.
<?php

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

Method 3: Multiple WHERE Condition with Model Scopes


The next method is to define your condition from within the Model class itself, this way you will be able to have a more expressive and elegant syntax.
<?php // app/Models/Post.php

class Post extends Model
{
    public function scopeActivePost($query)
    {
        return $query
            ->where('post_status', '=', 1)
            ->where('user_id', '=', 1);
    }

    public function scopeMainUser($query)
    {
        return $query
            ->where('post_status', '=', 1)
            ->where('user_id', '=', 1);
    }
}
Now in your controller or other parts of your application, you can call the scope while building the query.
<?php

Post::activePost()->mainUser()->get();

Method 4: Laravel Multiple WHERE Condition With Sub Query


The next method is to use a sub-query to define the WHERE condition and it will like below.
<?php

Post::query()
    ->where('post_status', '=', 1)
    ->whereNotNull('created_at')
    ->whereNotNull('updated_at')
    ->where(function($query){
        return $query
            ->whereNotNull('user_id')
            ->where('your_condition_here', '=', 'your_value_here');
    });
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻