php 54 lines · 7 steps

Validating coupons with Laravel's Pipeline

A checkout service runs a coupon through a chain of validation handlers, then applies the discount inside a transaction.

Explained by highlit
1<?php
2 
3namespace App\Services\Checkout;
4 
5use App\Models\Cart;
6use App\Models\Coupon;
7use App\Exceptions\CouponException;
8use Illuminate\Pipeline\Pipeline;
9use Illuminate\Support\Facades\DB;
10 
11class CouponResolver
12{
13 protected array $handlers = [
14 Handlers\EnsureCouponIsActive::class,
15 Handlers\EnsureWithinUsageLimit::class,
16 Handlers\EnsureMinimumSpend::class,
17 Handlers\EnsureCartEligibility::class,
18 Handlers\ApplyDiscountAmount::class,
19 ];
20 
21 public function __construct(protected Pipeline $pipeline)
22 {
23 }
24 
25 public function apply(Cart $cart, string $code): DiscountResult
26 {
27 $coupon = Coupon::where('code', strtoupper($code))->first();
28 
29 if (! $coupon) {
30 throw CouponException::notFound($code);
31 }
32 
33 return DB::transaction(function () use ($cart, $coupon) {
34 $context = new DiscountContext(
35 cart: $cart,
36 coupon: $coupon,
37 subtotal: $cart->subtotal(),
38 );
39 
40 $resolved = $this->pipeline
41 ->send($context)
42 ->through($this->handlers)
43 ->thenReturn();
44 
45 $coupon->increment('times_redeemed');
46 
47 return new DiscountResult(
48 coupon: $coupon,
49 discount: $resolved->discount,
50 total: max(0, $context->subtotal - $resolved->discount),
51 );
52 });
53 }
54}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A pipeline turns a tangle of validation checks into an ordered, individually testable list of handlers.
  2. 2Wrapping the read, mutation, and result in a single transaction keeps redemption counts consistent under concurrent use.
  3. 3Passing a mutable context object through each stage lets handlers accumulate state like the computed discount.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating coupons with Laravel's Pipeline — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code