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

lat4732's avatar
Level 12

How to optimize this code

Hey!

We're using Laravel Cashier (Stripe) and we have the following middleware on each route

$user = Cashier::findBillable(auth()->user()->stripe_id);
if(auth()->user()->stripe_id != null) {
    if($user->invoicesIncludingPending(['status' => 'open'])) {
        $invoices = $user->invoicesIncludingPending(['status' => 'open']);
        
        if(count($invoices) > 0) {
            if(!Route::is('view.related.company.inactive.account')) {
                return redirect()->route('view.related.company.inactive.account');
            }            
        }
    }
}

return $next($request);

Is there a way to optimize this code to avoid sending API request to stripe on every page load?

0 likes
2 replies
aleahy's avatar

For starters, the first line should be inside the if block.

But otherwise, you could record a session variable, or a value in the database, as to whether the user should be redirected after the first attempt. Have your middleware check for the presence of this value first, and if it is present, then you don't need to connect to stripe.

lat4732's avatar
lat4732
OP
Best Answer
Level 12

What I've done is:

  1. Create unpaid_invoices (user_id, invoice_id) table
  2. In StripeEventListener
if($event->payload['type'] == 'invoice.finalized') {
     // INSERT USER AND INVOICE_ID INTO UNPAID_INVOICES TABLE
}
if($event->payload['type'] == 'invoice.paid') {
try {
DB::table('unpaid_invoices')->where('invoice_id', $event->payload['data']['object']['id'])->delete();
} catch(\Exception $ex) {
     abort(500);
}
}

And then check with the middleware if there is existing row for auth user id. It's working pretty well.

Please or to participate in this conversation.