Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jksantos's avatar

Laravel API slow query

Guys, how are you?

I have a problem with an API I made for a client. This API consists of querying an endpoint every 2s to see if there are notes. Whenever a query is performed, it needs to be completed for another to be started, that is, they do not accumulate.

route:

Route::get('notes/{tenant}', [InvoiceController::class, 'index']);

controller:

public function index(string $tenant)
     {
         $invoice = Invoice::where([
             ['status', 'process'], ['tenant', $tenant]
         ])->first();
        
         if ($invoice) {
             $data['data'] = new InvoiceResource($invoice);
         } else {
             $data['data'] = [];
         }

         return response()->json($data); 
     }

The problem is that until today the client has not issued any notes, that is, the bank is empty, but sometimes this query takes up to 21s.

image that shows more details of the log: https://imgur.com/a/A1AGjrh

0 likes
7 replies
MohamedTammam's avatar

How many records inside the the invoices table? If you run the query directly in the database, how much time it takes? What's inside InvoiceResource?

jksantos's avatar

@MohamedTammam at this moment the table has no records. The query usually takes milliseconds, but in rare cases it takes more than 20s So far, the InvoiceResource has not been activated once because it does not have data in the table, but it only performs the data in our language: Portuguese.

MohamedTammam's avatar

@jksantos Then the problem might be with the server not with that request. Do you face any other delays anywhere else?

marian_d_dev's avatar

Instead of querying every 2 seconds, a better solution would be to create an Event, maybe name it InvoiceGenerated, and trigger it when an invoice is created. Also, create a Listener for this event and inside the listener add the logic that you need, like sending a notification with "invoice generated" message.

https://laravel.com/docs/10.x/events#introduction

jksantos's avatar

@marian_d_dev So, in this case, I think I didn't explain it right. Those who make the appointment to see if they have grades are my clients. Due to tax rules, this note has to be issued at the time it is created. So we created this API so that their internal system can check the existence of the note and issue it.

In short: I create a note and my client queries our API to issue it internally, if it exists.

Sorry for my bad english.

wafto's avatar

Seems more a connection problem with the database.

Please or to participate in this conversation.