Home > Net >  How can I store the conditions of a query Laravel
How can I store the conditions of a query Laravel

Time:09-22

How can I store the conditions of a query into a variable so that I can call it later? I have a get method that returns a Builder, not a collection.

if($a == 1) {
  $query = Review::query()
                  //many completely different conditions
                  ->where('product_id', $data['product_id']);
}
if($a == 2) {
  $query = Review::query()
                  //many completely different conditions
                  ->where('product_id', $data['product_id']);
}
$reviews = $query->get();

CodePudding user response:

You can use when()

$query = Review::query()
    ->when($a == 1, function($query){
        $query->where('', '');
    })
    ->when($a == 2, function($query){
        $query->where('', '');
    })
    ->where('product_id', $data['product_id'])
    ->get();
  • Related