Nagesh
Nagesh

Reputation: 437

Overriding where conditions in Laravel Query builder

I am working on E-Commerce application, in which I am fetching the product which has the status 1. But there are situations where I need to fetch the product which has status 2 or 3.

I have overridden the newQuery method and added a condition for status 1 in that method. Now I want to add another condition for status 2, but when I add this condition, the where clause will be duplicated in SQL query for that column(the default behavior of query builder).

Below is my code,

public function newQuery($excludeDeleted = true) {
    return parent::newQuery($excludeDeleted)
     ->where('status', 1);                
}

When I need to fetch the product with status 2 as below

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

then the query formed will be as below

select * from `products` where `status` = 1 and `status` = 2

But I need an output like below query

select * from `products` where `status` = 2

Please suggest the way of doing it.

Upvotes: 0

Views: 1562

Answers (1)

LegenJerry
LegenJerry

Reputation: 414

Add a parameter to the newQuery function and pass in the status. When calling the newQuery function the default status would be 1, but if you supply an argument it will be whatever you pass to it.

public function newQuery($excludeDeleted = true, $status = 1) {
    return parent::newQuery($excludeDeleted)
        ->where('status', $status);                
}

EDIT

This may be possible using Dynamic Local Query Scope:

//Model

public function scopeStatus($query, $status = 1)
{
    return $query->where('status', $status);
}

and call like:

$result = App\MyModel::status(2)->get();
//OR To get with default "status"
$result = App\MyModel::status()->get();

Upvotes: 2

Related Questions