php
49 lines · 7 steps
Validating coupons before applying a discount in Laravel
A Laravel service runs a coupon through every eligibility check before computing the discount it earns.
Explained by
highlit
1<?php
2
3namespace App\Services;
4
5use App\Models\Coupon;
6use App\Models\Order;
7use App\Exceptions\CouponException;
8use Carbon\Carbon;
9
10class CouponValidator
11{
12 public function apply(string $code, Order $order): float
13 {
14 $coupon = Coupon::where('code', strtoupper(trim($code)))->first();
15
16 if (! $coupon || ! $coupon->is_active) {
17 throw new CouponException('This coupon code is not valid.');
18 }
19
20 if ($coupon->expires_at !== null && $coupon->expires_at->isPast()) {
21 throw new CouponException('This coupon has expired.');
22 }
23
24 if ($coupon->starts_at !== null && $coupon->starts_at->isFuture()) {
25 throw new CouponException('This coupon is not active yet.');
26 }
27
28 if ($coupon->max_uses !== null && $coupon->times_used >= $coupon->max_uses) {
29 throw new CouponException('This coupon has reached its usage limit.');
30 }
31
32 if ($coupon->onlyOncePerCustomer() && $order->customer->hasUsedCoupon($coupon)) {
33 throw new CouponException('You have already used this coupon.');
34 }
35
36 if ($order->subtotal < $coupon->min_order_total) {
37 throw new CouponException(sprintf(
38 'A minimum order of %s is required to use this coupon.',
39 money_format($coupon->min_order_total)
40 ));
41 }
42
43 $discount = $coupon->type === 'percent'
44 ? round($order->subtotal * ($coupon->value / 100), 2)
45 : min($coupon->value, $order->subtotal);
46
47 return $discount;
48 }
49}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Stacking guard clauses keeps each business rule isolated and the happy path unindented at the bottom.
- 2Normalizing user input like the coupon code before lookup avoids false negatives from casing or whitespace.
- 3Separating validation from calculation means the discount math only runs once the coupon is fully proven valid.
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\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 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-before-applying-a-discount-in-laravel-explained-php-0393/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.