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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A pipeline turns a tangle of validation checks into an ordered, individually testable list of handlers.
- 2Wrapping the read, mutation, and result in a single transaction keeps redemption counts consistent under concurrent use.
- 3Passing a mutable context object through each stage lets handlers accumulate state like the computed discount.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/validating-coupons-with-laravel-s-pipeline-explained-php-4927/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.