Jitendra Parmar Jitendra Parmar - 1 month ago 8
PHP Question

How to write conditional query in laravel 5.2?

How can I write this kind of queries in laravel 5.2 eloquent or query builder?

$query = Customers::leftjoin('Query string');
if(condation)
{
//This part added to query
}
else
{
//This part added to query
}
->get();

Answer

You have to remember your query in a variable, I.E. like this:

$query = Customers::leftjoin('Query string');   

if(condation){
    $query = $query->where('something', '=', 'something');
} else {
    $query = $query->where('somethingelse', '=', 'somethingelse');
}

$query = $query->get();

Normally you would have $query->where()-get();, which is basically the same thing, $query will hold the result of your ->where() and allows you to chain further on $query

Comments