I want to check if user is subscribed, then swap, else create the subscription.
When I move the swap inside the if and newsubscription inside the else, I get no such plan: premium
Apr 26, 2020
4
Level 1
Call to a member function swap() on null - Laravel cashier subscription
I am creating a subscription using laravel cashier and stripe.
I am not using the user model, but using employer model. I have added the billable trait, set CASHIER_MODEL=App\Employer in my .env. Done all that is required but I get below error when making payments.
Call to a member function swap() on null
My codes
try {
// get plan
$plan = Plan::where('slug', $request->slug)->first();
$getEmployer = auth('employer')->user();
$stripeCustomer = $getEmployer->createOrGetStripeCustomer();
$updateStripeCustomer = $getEmployer->updateStripeCustomer([
'name' => $getEmployer->fname ." " .$getEmployer->lname,
'email' => $getEmployer->email,
'phone' => $getEmployer->phone,
]);
// get paymentMethod
$paymentMethod = $request->paymentMethod;
if ($getEmployer->hasDefaultPaymentMethod()) {
$getEmployer->updateDefaultPaymentMethod($paymentMethod);
}else{
$getEmployer->addPaymentMethod($paymentMethod);
}
// check if user is already subscribed, then swap
if ($getEmployer->subscribed('main')) {
// charge if new subscriber
$charge = $getEmployer->newSubscription('main', $plan->stripe_plan)->create($paymentMethod, [
'email' => $getEmployer->email,
]);
// save new subscription status
$getEmployer->plan_id = $plan->id;
$getEmployer->save();
// Mail
event(new SubscriptionMail($getEmployer));
\Session::flash('success', 'You have upgraded to the '.$plan->plan_type.' plan');
return redirect()->route('employer.dashboard');
}else{
$getEmployer->subscription('main')->swap($plan->stripe_plan);
event(new SubscriptionMail($getEmployer));
\Session::flash('success', 'You have changed to the '.$plan->plan_type.' plan');
return redirect()->route('employer.dashboard');
}
} catch (\Exception $e) {
\Session::flash('error',$e->getMessage());
return back();
}
Level 10
so, if you want to swap subscription IF user IS subscribed you need to do this inside if block, as code inside else block is executed when user IS NOT subscribed. And the message actually tells you that problem is about something else - you don't have plan "premium"
Please or to participate in this conversation.