Subscription billing is the part of a SaaS app you can’t ship half-done. Laravel Cashier Stripe integration gives you a clean API for the happy path (start a trial, charge monthly, swap plans), but the work that matters sits around it: who gets into the app while a card is failing, what happens when someone cancels in week two, and how your database finds out that Stripe changed something. This post builds that around Cashier, with original code and tests that run without touching Stripe.
It’s the billing side of the product architecture I described in the multi-tenant SaaS architecture guide. I’ll cover plans, a trial, access gating, plan changes with proration, cancellation, and webhooks, including one event Cashier doesn’t handle for you. The official Cashier documentation remains the reference for everything not shown here.
What this post covers
- Tested versions
- Setting up Cashier
- Keeping plans in one place
- Starting a subscription with a trial
- Gating access: trials, grace periods and past due
- Changing plans and proration
- Cancelling without cutting people off
- Webhooks and failed payments
- Testing without calling Stripe
- What I did not test
- FAQ
Tested versions
| Tool | Version |
|---|---|
| Laravel Framework | 13.43.0 (fresh laravel/laravel skeleton) |
| Laravel Cashier | 16.11.0 |
| stripe/stripe-php | 21.3.3 (installed by Cashier) |
| PHP | 8.4.27 CLI |
| PHPUnit | 12.5.43: 22 billing tests passing (24 tests, 62 assertions in the whole app) |
| Database | SQLite in memory for tests |
My test box had no bcmath extension, which Cashier’s money library requires, so I installed phpseclib/bcmath_compat there to get past Composer’s check. On a real server, enable ext-bcmath instead and skip the polyfill. The tests never call Stripe’s servers, as explained in the testing section below.
Setting up Cashier
Install the package, publish its migrations, and migrate. The migrations add customer columns to users and create the subscriptions and subscription_items tables.
composer require laravel/cashier
php artisan vendor:publish --tag="cashier-migrations"
php artisan migrate
Add the Billable trait to the model that pays. Here it’s User, but if your customer is a team or workspace, put it there instead. That is a tenancy decision, not a billing one. Then add your keys to .env:
STRIPE_KEY=pk_test_...
STRIPE_SECRET=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_PRICE_STARTER=price_...
STRIPE_PRICE_GROWTH=price_...
#[Fillable(['name', 'email', 'password'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use Billable, HasFactory, Notifiable;
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
/** The plan on the user's default subscription, or null. */
public function currentPlan(): ?Plan
{
return Plan::fromPriceId($this->subscription('default')?->stripe_price);
}
}
The currentPlan() helper at the bottom is mine, not Cashier’s. It turns the price ID stored on the subscription back into an enum, so the rest of the app never compares raw price_... strings.
Keeping plans in one place
A price ID belongs in config, not scattered through controllers. A small config file and a backed enum give you one place to look and one place to test:
<?php
return [
// One entry per plan. The Stripe price IDs come from your dashboard.
'plans' => [
'starter' => ['price' => env('STRIPE_PRICE_STARTER')],
'growth' => ['price' => env('STRIPE_PRICE_GROWTH')],
],
'trial_days' => 14,
];
<?php
namespace App\Enums;
enum Plan: string
{
case Starter = 'starter';
case Growth = 'growth';
public function priceId(): string
{
return config("billing.plans.{$this->value}.price")
?? throw new \RuntimeException("No Stripe price configured for {$this->value}.");
}
public static function fromPriceId(?string $priceId): ?self
{
foreach (self::cases() as $plan) {
if ($priceId !== null && config("billing.plans.{$plan->value}.price") === $priceId) {
return $plan;
}
}
return null;
}
}
If a price is missing from .env, priceId() throws straight away. I’d rather get a clear error than send a null price to Stripe.
Starting a subscription with a trial
The controller validates the plan against the enum, refuses to create a second subscription, and starts a card-on-file trial. Cashier creates the Stripe customer if there isn’t one, attaches the payment method, and creates the subscription:
public function store(Request $request): RedirectResponse
{
$data = $request->validate([
'plan' => ['required', Rule::enum(Plan::class)],
'payment_method' => ['required', 'string'],
]);
$user = $request->user();
abort_if($user->subscribed('default'), 409, 'Already subscribed.');
try {
$user->newSubscription('default', Plan::from($data['plan'])->priceId())
->trialDays(config('billing.trial_days'))
->create($data['payment_method']);
} catch (IncompletePayment $e) {
// 3D Secure or similar: send them to Cashier's confirmation page.
return redirect()->route('cashier.payment', [
$e->payment->id,
'redirect' => route('billing.show'),
]);
}
return redirect()->route('billing.show');
}
IncompletePayment is thrown when a charge needs extra confirmation, such as 3D Secure. Cashier ships a payment page for that, which is what the redirect points to. Because this is a trial, the first charge happens when the trial ends. Any extra confirmation needed then reaches you through the invoice.payment_action_required webhook, which Cashier has a handler for.
This test asserts what was actually sent to Stripe: the right price, a trial end about 14 days away, and a local subscription that reports as trialing.
public function test_subscribing_starts_a_trial_on_the_chosen_plan(): void
{
$user = User::factory()->create();
$this->actingAs($user)
->post('/billing/subscribe', ['plan' => 'starter', 'payment_method' => 'pm_card_visa'])
->assertRedirect('/billing');
$sent = $this->stripe->sent('post', '/v1/subscriptions')[0]['params'];
$this->assertSame('price_starter_test', $sent['items'][0]['price']);
$this->assertEqualsWithDelta(now()->addDays(14)->timestamp, $sent['trial_end'], 5);
$subscription = $user->fresh()->subscription('default');
$this->assertTrue($subscription->onTrial());
$this->assertSame(Plan::Starter, $user->fresh()->currentPlan());
$this->assertSame('cus_fake_1', $user->fresh()->stripe_id);
}
Gating access: trials, grace periods and past due
Cashier’s subscribed() check is the right gate for most apps, because it already counts a trial and a cancellation grace period as valid. A thin middleware wraps it so you can return a redirect for browsers and a 402 for API clients:
class EnsureSubscribed
{
public function handle(Request $request, Closure $next): Response
{
// subscribed() is true while trialing, active, or on a cancellation grace period.
if ($request->user()?->subscribed('default')) {
return $next($request);
}
if ($request->expectsJson()) {
return response()->json(['message' => 'An active subscription is required.'], 402);
}
return redirect()->route('billing.show')
->with('status', 'Choose a plan to keep using the app.');
}
}
Here is how the states I tested map to access:
| Subscription state | Gets in? |
|---|---|
| No subscription | No, redirected to billing (402 for JSON) |
active | Yes |
trialing with a future trial_ends_at | Yes |
Cancelled, ends_at in the future (grace period) | Yes |
Cancelled, ends_at in the past | No |
past_due | No, by default |
The last row is a product decision. By default Cashier treats past_due as not valid, so a customer whose renewal failed loses access immediately. Some teams prefer a few days of leeway. Cashier has a static Cashier::keepPastDueSubscriptionsActive() switch for that, and the Cashier docs cover it. I kept the strict default and tested it, so the choice is visible instead of accidental.
Keep this gate for “is the account paid up” and nothing else. Per-plan features such as seat limits belong in a separate check, and gradual rollouts of those features belong with feature flags.
Changing plans and proration
swap() moves a subscription to another price. By default Cashier asks Stripe to create prorations, so the customer is credited for the unused part of the old price and charged for the new one on the next invoice. The controller lets a caller opt out for downgrades, where you may prefer the new price to start cleanly at the next cycle:
public function update(Request $request): RedirectResponse
{
$data = $request->validate([
'plan' => ['required', Rule::enum(Plan::class)],
'prorate' => ['sometimes', 'boolean'],
]);
$subscription = $request->user()->subscription('default');
abort_if($subscription === null, 404);
// Prorate by default. A downgrade can opt out and simply start on the next invoice.
if ($request->boolean('prorate', true) === false) {
$subscription->noProrate();
}
$subscription->swap(Plan::from($data['plan'])->priceId());
return redirect()->route('billing.show');
}
Two tests pin the behavior down. One asserts proration_behavior is create_prorations and the local price changes; the other asserts it is none when prorate=false. The Stripe proration guide describes what each option does on the invoice. Also note that swapping a subscription that is still in its trial keeps the original trial end, because Cashier passes it back to Stripe.
public function test_changing_plan_prorates_by_default(): void
{
$user = $this->subscribedUser();
$this->actingAs($user)->patch('/billing/plan', ['plan' => 'growth'])->assertRedirect('/billing');
$params = $this->stripe->sent('post', '/v1/subscriptions/sub_fake_1')[0]['params'];
$this->assertSame('create_prorations', $params['proration_behavior']);
$this->assertSame('price_growth_test', $params['items'][0]['price']);
$this->assertSame(Plan::Growth, $user->fresh()->currentPlan());
}
Cancelling without cutting people off
cancel() doesn’t end the subscription now. It sets cancel_at_period_end on Stripe and stores an ends_at locally, which is the end of the paid period, or the end of the trial if they were still on one. Until that date the user is on a grace period and still passes subscribed(). That is the behavior people expect from “cancel my plan”, and the test checks both halves: the flag that went to Stripe and the grace period that opened locally.
public function test_cancelling_keeps_access_until_the_trial_ends(): void
{
$user = $this->subscribedUser();
$this->actingAs($user)->delete('/billing')->assertRedirect('/billing');
$params = $this->stripe->sent('post', '/v1/subscriptions/sub_fake_1')[0]['params'];
$this->assertSame('true', $params['cancel_at_period_end']);
$subscription = $user->fresh()->subscription('default');
$this->assertTrue($subscription->onGracePeriod());
$this->assertTrue($user->fresh()->subscribed('default'));
}
Webhooks and failed payments
Your database only knows what Stripe tells it. Renewals, failed charges, cancellations from the Stripe dashboard and card updates all arrive as webhooks, so this is the part of laravel cashier stripe setups that deserves the most care. Cashier registers a POST /stripe/webhook route and mirrors subscription events into your tables. Three things to set up:
- Exclude the route from CSRF checks:
$middleware->validateCsrfTokens(except: ['stripe/*'])inbootstrap/app.php. - Set
STRIPE_WEBHOOK_SECRET. When it is set, Cashier verifies the signature and rejects anything unsigned. That’s the same idea as in my guide to verifying and processing webhooks safely. - Extend Cashier’s controller for anything it doesn’t cover.
Cashier has handlers for subscription created, updated and deleted, customer updates, invoice.payment_succeeded and invoice.payment_action_required, among others. It has no handler for invoice.payment_failed, which is the one that tells you a renewal charge was declined. Cashier finds a handler by turning the event name into a method name, so adding one is a single method:
class StripeWebhookController extends CashierController
{
/**
* Cashier does not handle invoice.payment_failed, so we add it.
* Cashier finds this method by turning the event type into a name.
*/
protected function handleInvoicePaymentFailed(array $payload): Response
{
$invoice = $payload['data']['object'];
if ($user = $this->getUserByStripeId($invoice['customer'])) {
$user->notify(new PaymentFailed(
attempt: (int) ($invoice['attempt_count'] ?? 1),
amountDue: (int) $invoice['amount_due'],
currency: $invoice['currency'],
invoiceUrl: $invoice['hosted_invoice_url'] ?? null,
));
}
return $this->successMethod();
}
}
To use the subclass, register the same method and URI in routes/web.php. Your route is registered later than Cashier’s, so it replaces it, and the test below proves ours is the one that runs:
Route::post('/stripe/webhook', [StripeWebhookController::class, 'handleWebhook'])
->name('cashier.webhook');
The notification formats the amount from minor units and links to Stripe’s hosted invoice page, where the customer can fix their card. It is a plain notification, so you can implement ShouldQueue on it and let your queue workers send the email.
public function toMail(object $notifiable): MailMessage
{
$amount = number_format($this->amountDue / 100, 2).' '.strtoupper($this->currency);
return (new MailMessage)
->subject('Your payment did not go through')
->line("We could not collect {$amount} (attempt {$this->attempt}).")
->when($this->invoiceUrl, fn (MailMessage $m) => $m->action('Update your card', $this->invoiceUrl));
}
The webhook tests build a real signed request, using the same t=...,v1=... HMAC format Stripe sends, and check five outcomes: a wrong signature gets a 403 and writes nothing; a dashboard-created subscription is mirrored locally; a deleted subscription ends access; an update to past_due closes the gate; and a failed payment emails the right customer with the right amount.
private function sendEvent(string $type, array $object, ?string $secret = self::SECRET)
{
$payload = json_encode(['id' => 'evt_1', 'type' => $type, 'data' => ['object' => $object]]);
$timestamp = time();
$signature = hash_hmac('sha256', "{$timestamp}.{$payload}", $secret);
return $this->call('POST', '/stripe/webhook', [], [], [], [
'CONTENT_TYPE' => 'application/json',
'HTTP_STRIPE_SIGNATURE' => "t={$timestamp},v1={$signature}",
], $payload);
}
public function test_a_failed_payment_emails_the_customer(): void
{
Notification::fake();
$user = User::factory()->create(['stripe_id' => 'cus_wh_1']);
$this->sendEvent('invoice.payment_failed', [
'customer' => 'cus_wh_1',
'attempt_count' => 2,
'amount_due' => 4900,
'currency' => 'usd',
'hosted_invoice_url' => 'https://pay.example.test/inv_1',
])->assertOk();
Notification::assertSentTo($user, PaymentFailed::class, function (PaymentFailed $n) use ($user) {
$mail = $n->toMail($user);
return $n->attempt === 2
&& $n->amountDue === 4900
&& str_contains(implode(' ', $mail->introLines), '49.00 USD');
});
}
Webhooks can arrive twice, or out of order. Cashier’s subscription handlers look rows up by Stripe ID, so a repeated event doesn’t create duplicates. If you add side effects of your own, such as sending that email, decide whether sending twice is acceptable or store the event ID and skip repeats.
Testing without calling Stripe
Cashier talks to Stripe through the official SDK, and the SDK lets you swap its HTTP client. My FakeStripe class implements that one-method interface, records every request, and returns canned JSON for the handful of endpoints the flow needs. Tests can then assert on what Cashier sent. This is the same idea as Http::fake for Laravel’s own HTTP client, one level down.
class FakeStripe implements ClientInterface
{
/** @var list<array{method: string, path: string, params: array}> */
public array $requests = [];
private array $items = [];
public static function install(): self
{
$fake = new self;
ApiRequestor::setHttpClient($fake);
return $fake;
}
public function request($method, $absUrl, $headers, $params, $hasFile, $apiMode = 'v1', $maxNetworkRetries = null)
{
$path = parse_url($absUrl, PHP_URL_PATH);
$this->requests[] = ['method' => $method, 'path' => $path, 'params' => $params ?? []];
$body = match (true) {
$method === 'post' && $path === '/v1/customers' => $this->customer(),
in_array($method, ['get', 'post'], true) && str_starts_with($path, '/v1/customers/') => $this->customer(),
str_starts_with($path, '/v1/payment_methods/') => $this->paymentMethod($path),
$method === 'post' && $path === '/v1/subscriptions' => $this->createSubscription($params),
$method === 'get' && str_starts_with($path, '/v1/subscriptions/') => $this->subscription('trialing'),
$method === 'post' && str_starts_with($path, '/v1/subscriptions/') => $this->updateSubscription($params),
$method === 'get' && str_starts_with($path, '/v1/subscription_items/') => $this->subscriptionItem(),
default => throw new \RuntimeException("Unexpected Stripe call: $method $path"),
};
return [json_encode($body), 200, []];
}
A call it doesn’t know throws, which means a new Cashier call in a future version fails loudly instead of silently passing.
What I did not test
- Real Stripe responses. The fake returns the fields Cashier reads, not everything Stripe sends. Before launch, run the same flows once in Stripe’s test mode with its test cards.
- The 3D Secure path.
IncompletePaymentand Cashier’s confirmation page need Stripe’s real confirmation step. - Stripe’s retry schedule for failed invoices. That is configured in the Stripe dashboard, not in your code, so your tests should only cover how you react to its events.
- Taxes, invoices as PDFs, and metered billing. Cashier supports them, and none are used here.
FAQ
How do I add a free trial with Laravel Cashier?
Call trialDays() on the subscription builder before create(). Cashier sends the trial end to Stripe and stores trial_ends_at on the local subscription, so onTrial() and subscribed() are true until it passes.
Do I need webhooks if Cashier already updates the subscription?
Yes. Cashier updates your database during requests you make, such as subscribing or swapping. Renewals, failed charges and dashboard changes happen without a request from your app, and only webhooks tell you about them.
What happens to access when a renewal payment fails?
The subscription becomes past_due after Stripe’s webhook arrives, and with Cashier’s default it stops counting as valid. You can keep it valid for a while with Cashier::keepPastDueSubscriptionsActive() if that fits your product.
How do I handle a Stripe event Cashier doesn’t?
Extend Cashier’s WebhookController and add a handle... method named after the event, such as handleInvoicePaymentFailed. Then point POST /stripe/webhook at your subclass.
Should I pass Stripe payloads around as arrays?
I’d map the few fields you need into a small typed object at the edge, the way I did for webhooks in using data transfer objects in Laravel. This post keeps arrays to stay close to Cashier’s own handlers.
I’m Shahrukh Akhtar (Shaz3e), CTO & Co-Founder of Diligent Creators Pvt. Ltd., a Technology Executive & Product Builder. I run client delivery and build SaaS products, including EloSync. You can find me on X, LinkedIn, Peerlist and GitHub.
