php 49 lines · 7 steps

How a queued weekly digest email works in Laravel

A Laravel notification that queues itself, formats a summary of recent activity, and mails it out with a randomized delay.

Explained by highlit
1<?php
2 
3namespace App\Notifications;
4 
5use Illuminate\Bus\Queueable;
6use Illuminate\Contracts\Queue\ShouldQueue;
7use Illuminate\Notifications\Messages\MailMessage;
8use Illuminate\Notifications\Notification;
9use Illuminate\Support\Collection;
10 
11class WeeklyDigestNotification extends Notification implements ShouldQueue
12{
13 use Queueable;
14 
15 public function __construct(private Collection $activities)
16 {
17 $this->onQueue('notifications');
18 }
19 
20 public function via(object $notifiable): array
21 {
22 return ['mail'];
23 }
24 
25 public function toMail(object $notifiable): MailMessage
26 {
27 $message = (new MailMessage)
28 ->subject('Your weekly digest, '.$notifiable->first_name)
29 ->greeting("Hi {$notifiable->first_name},")
30 ->line('Here is what happened across your workspace this week.');
31 
32 $this->activities
33 ->sortByDesc('occurred_at')
34 ->take(10)
35 ->each(fn ($activity) => $message->line(
36 "\u{2022} {$activity->summary} ({$activity->occurred_at->diffForHumans()})"
37 ));
38 
39 return $message
40 ->action('Open dashboard', route('dashboard'))
41 ->line('You are receiving this because you opted into weekly summaries.')
42 ->salutation('See you next week,');
43 }
44 
45 public function withDelay(object $notifiable): array
46 {
47 return ['mail' => now()->addSeconds(random_int(0, 300))];
48 }
49}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing ShouldQueue lets a notification run in the background instead of blocking the request.
  2. 2Notification channels and message content are declared separately, keeping delivery and formatting concerns clean.
  3. 3Spreading dispatch times with a randomized delay smooths load spikes when many notifications fire at once.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a queued weekly digest email works in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code