In my controller I have a have a function to check subscription status and update it in my database. The problem is with 50000 users, it takes too long to finish and times out.
JavaScript
x
public function UpdateStatus(){
$users = User::all();
foreach($users as $user){
$user->createOrGetStripeCustomer();
$stripeSubs = $user->asStripeCustomer()->subscriptions->all();
$dbSubs = DB::table('subscriptions')->select('stripe_id')->where('user_id', $user->id)->get();
foreach($dbSubs as $check){
$canDelete=0;
foreach($stripeSubs as $value){
if($check->stripe_id == $value->id){
$canDelete++;
}
}
if($canDelete==0){
DB::table('subscriptions')->where('user_id', $user->id)->where('stripe_id',$check->stripe_id)->update(['stripe_status'=>'ended']);
}
}
}
return redirect('/dashboard');
}
I’m sure I shouldn’t even process that many at a time but I kinda got stuck here and am not sure how exactly to approach this. My goal is to make this work and optimize it.
Advertisement
Answer
you use job like that:
JavaScript
php artisan make:job checkSubscrption
in your env file change Queue_CONNECTiON=database
,
run php artisan queue:table
and php artisan migrate
in your checkSubscription file set that
JavaScript
public function handle(){
$users = User::all();
foreach($users as $user){
$user->createOrGetStripeCustomer();
$stripeSubs = $user->asStripeCustomer()->subscriptions->all();
$dbSubs = DB::table('subscriptions')->select('stripe_id')->where('user_id', $user->id)->get();
foreach($dbSubs as $check){
$canDelete=0;
foreach($stripeSubs as $value){
if($check->stripe_id == $value->id){
$canDelete++;
}
}
if($canDelete==0){
DB::table('subscriptions')->where('user_id', $user->id)->where('stripe_id',$check->stripe_id)->update(['stripe_status'=>'ended']);
}
}
}}
in your controller:
JavaScript
public function UpdateStatus(){
checkSubscrption::dispatch();//you can use chunk method and pass your $users as params
return redirect('/dashboard');}
then run php artisan queue:work