php
46 lines · 7 steps
Delayed, self-cancelling emails in Laravel
A queued Laravel notification that waits six hours, then only sends if the cart is still abandoned.
Explained by
highlit
1<?php
2
3namespace App\Notifications;
4
5use App\Models\Cart;
6use Illuminate\Bus\Queueable;
7use Illuminate\Contracts\Queue\ShouldQueue;
8use Illuminate\Notifications\Messages\MailMessage;
9use Illuminate\Notifications\Notification;
10
11class AbandonedCartReminder extends Notification implements ShouldQueue
12{
13 use Queueable;
14
15 public function __construct(public Cart $cart)
16 {
17 $this->delay(now()->addHours(6));
18 }
19
20 public function via(object $notifiable): array
21 {
22 return ['mail'];
23 }
24
25 public function shouldSend(object $notifiable, string $channel): bool
26 {
27 $cart = $this->cart->fresh();
28
29 return $cart !== null
30 && $cart->checked_out_at === null
31 && $cart->items()->exists();
32 }
33
34 public function toMail(object $notifiable): MailMessage
35 {
36 $total = $this->cart->items->sum(fn ($item) => $item->price * $item->quantity);
37
38 return (new MailMessage)
39 ->subject('You left something behind')
40 ->greeting("Hi {$notifiable->first_name},")
41 ->line('Your cart is still waiting for you.')
42 ->line("{$this->cart->items->count()} item(s) totalling $" . number_format($total, 2) . '.')
43 ->action('Complete your order', route('cart.show', $this->cart))
44 ->line('This cart will expire soon, so don\'t miss out!');
45 }
46}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Implementing ShouldQueue lets a notification run in the background so slow email work never blocks the request.
- 2A time delay plus a shouldSend guard turns a fire-and-forget message into a reminder that cancels itself when the condition passes.
- 3Re-fetching the model at send time avoids acting on stale state captured when the job was first queued.
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
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
php
class TwoFactorController extends Controller { public function show(Request $request): View|RedirectResponse {
Two-factor auth challenge flow in Laravel
authentication
two-factor
middleware
Intermediate
10 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/delayed-self-cancelling-emails-in-laravel-explained-php-0da9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.