Home > database >  Laravel Query in if else converting to common query
Laravel Query in if else converting to common query

Time:11-23

this is my code I want to convert this query in to a common query

 if ($limit == 0) {
   $response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->get();
   } else {
  $response = WebhookErrorNotification::where('is_error', true)->orderByDesc('id')->limit($limit)->get();
            }

CodePudding user response:

You can save the query in a variable above the if/else statement. So something like this would work. Now if this is not the answer you are looking for please specify what you mean by common query!

$query = WebhookErrorNotification::where('is_error', true)->orderByDesc('id');
if ($limit == 0) {
  $response = $query->get();
} else {
  $response = $query->limit($limit)->get();
}

CodePudding user response:

you can do something like this

$response = WebhookErrorNotification::where('is_error', true)
    ->when($limit !== 0, function ($query) use ($limit) {
        $query->limit($limit);
    })->orderByDesc('id')->get();
  • Related