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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing ShouldQueue lets a notification run in the background so slow email work never blocks the request.
  2. 2A time delay plus a shouldSend guard turns a fire-and-forget message into a reminder that cancels itself when the condition passes.
  3. 3Re-fetching the model at send time avoids acting on stale state captured when the job was first queued.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Delayed, self-cancelling emails in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code