php 48 lines · 6 steps

Building a queued digest email in Laravel

A Mailable that queues a weekly comment digest, pluralizes its subject, and groups comments by thread.

Explained by highlit
1<?php
2 
3namespace App\Mail;
4 
5use App\Models\Comment;
6use App\Models\User;
7use Illuminate\Bus\Queueable;
8use Illuminate\Contracts\Queue\ShouldQueue;
9use Illuminate\Mail\Mailable;
10use Illuminate\Mail\Mailables\Content;
11use Illuminate\Mail\Mailables\Envelope;
12use Illuminate\Queue\SerializesModels;
13use Illuminate\Support\Collection;
14 
15class WeeklyCommentDigest extends Mailable implements ShouldQueue
16{
17 use Queueable, SerializesModels;
18 
19 public function __construct(
20 public User $user,
21 public Collection $comments,
22 ) {}
23 
24 public function envelope(): Envelope
25 {
26 return new Envelope(
27 subject: trans_choice(
28 '{1} 1 new comment this week|[2,*] :count new comments this week',
29 $this->comments->count(),
30 ['count' => $this->comments->count()],
31 ),
32 );
33 }
34 
35 public function content(): Content
36 {
37 return new Content(
38 markdown: 'emails.comments.weekly-digest',
39 with: [
40 'greetingName' => $this->user->first_name,
41 'grouped' => $this->comments
42 ->sortByDesc('created_at')
43 ->groupBy(fn (Comment $comment) => $comment->commentable->title),
44 'manageUrl' => route('notifications.preferences'),
45 ],
46 );
47 }
48}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing ShouldQueue lets a Mailable dispatch to a background queue instead of blocking the request.
  2. 2trans_choice picks the right singular or plural phrase based on a count for natural-sounding subjects.
  3. 3Collection methods let you sort and group model data into view-ready shapes right in the Mailable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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