Write Laravel Example to Write Multiple where conditions

Published January 17, 2022

In this post, we'll look at how to implement multiple where clauses in Laravel. Multiple where conditions are supported in both Database Query Builder and Eloquent Model.

Laravel has an inbuilt where() function that allows us to simply write numerous where conditions query on the Model or Database query builder.

The where() function may be written using the following syntax:

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

 

Example

Let’s look at an example of a simple where condition

 

$posts = Post::where('id', '=', 1)

             ->where('status', '=', 'active')

              ->get();

 

The above code is going to output the following SQL Query

 

select * from posts where id = 1 and status = 'active'

 

You can also pass an array as a condition. Check out the example below

$whereCondition = [

    ['status', '=', 'activate'],

    ['category', '=', 'account'],

    ['date', '>=', '2022-01-01'],

    ['date', '<=', '2022-01-05'],

];

$posts = Post::where($whereCondition)->get();

 

 

If you execute this code, the following will be displayed

select * from posts where status = 'activate' and category = 'account' and date >= '2022-01-01' and date <= '2022-01-05'

 

To Implement Multiple Where Condition in Laravel

In Laravel, we usually use the Query Scopes to implement the multiple conditions.  You can create scopeFunctioname to specify the scopes in your model. That is, you must precede the scope term with the function name. If you want to create a status method, for example, your scope will be scopeStatus. Let's look at an example.

We usually implement the where multiple conditions in the app/model.

Example

 

The following code can be used to select and post multiple items

 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model

{

    /**

     * Scope a query to only include popular posts.

     * https://www.scratchcode.io

     * @param  \Illuminate\Database\Eloquent\Builder  $query

     * @return \Illuminate\Database\Eloquent\Builder

     */

    public function scopeLikes($query)

    {

        return $query->where('likes', '>', 100);

    }

 

    /**

     * Scope a query to only include publish posts.

     * https://www.scratchcode.io

     * @param  \Illuminate\Database\Eloquent\Builder  $query

     * @return \Illuminate\Database\Eloquent\Builder

     */

    public function scopeStatus($query)

    {

        return $query->where('status', 'publish');

    }

}

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

277 Views