Posted: 11-08-2017

Write dynamic queries using Eloquent

Write dynamic queries using Eloquent

Eloquent ORM provides a very powerful interfaces to write dynamic queries

 ->when(condition, true callback, <optional false callback>)-

For example you can write a query like this:

$priceGroup = 'cheapest';

$products = \App\Product::select('name', 'price')
->when($priceGroup == 'cheapest',
function($q){
return $q->where('price','<', 10);
},
function($q){
return $q->where('price','>', 10);
}
);

dd($products->get());