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?
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.
What I've done is:
Create unpaid_invoices (user_id, invoice_id) table
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 sign in or create an account to participate in this conversation.