Sanjana Jayaweera
Sanjana Jayaweera

Reputation: 13

Laravel Query in if else converting to common query

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();
            }

Upvotes: 1

Views: 56

Answers (2)

Khayam Khan
Khayam Khan

Reputation: 1237

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();

Upvotes: 1

dz0nika
dz0nika

Reputation: 1021

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();
}

Upvotes: 1

Related Questions