Home / Snippets / How to Query Laravel Eloquent With Multiple WHERE Conditions?
How to Query Laravel Eloquent With Multiple WHERE Conditions? cover

How to Query Laravel Eloquent With Multiple WHERE Conditions?

692

2 years ago

0 comments

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');
    });
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this