Learn Laravel · 13/17

Mail & Notifications: Talking to Users

9 min read

📬 Laravel Mail & Notifications: Talking to Users

Hey there! Welcome to the guide on how to make your Laravel application talk. No, not like a chatbot (that's a whole other adventure), but by sending emails and notifications. It's how your app communicates important stuff to your users, like "Hey, you've got a new follower!" or the ever-so-critical "Here's your password reset link."

The Problem: A Silent Application is a Lonely Application

Imagine you sign up for a cool new web service. You enter your details, hit "Register," and... nothing. No welcome email, no confirmation, just silence. Did it work? Who knows! Users need feedback. They need to know their actions were successful and be alerted to important events. This is where mail and notifications come in; they are the voice of your application.


1. Configuring Mail Services (SMTP & Mailpit for local dev) 📮

Before your app can send its first email, it needs to know how to send it. You can't just yell "SEND EMAIL!" into the void and hope for the best. You need to connect to a mail delivery service.

What is SMTP?

SMTP stands for Simple Mail Transfer Protocol. Think of it as the postman of the internet. It's a standardized way for servers to send and receive emails. Your Laravel app will hand off its emails to an SMTP server, which then takes on the heroic task of delivering that email to your user's inbox.

The Local Development Dilemma 🚧

When you're building and testing your app, you'll be sending a lot of test emails. You definitely don't want to accidentally spam real email addresses (including your own) with hundreds of "Test Welcome Email #142". We need a way to see the emails our app is sending without them ever leaving our computer.

Solution: Mailpit, Your Magical Local Mailbox ✨

Mailpit is a fantastic tool that acts as a fake SMTP server. It catches any email your Laravel application sends and displays it in a clean web interface. It's like having a personal mailbox just for your development work. No more flooded inboxes!

Setting up Mailpit

Getting Mailpit running is a breeze with Docker.

  1. Install Docker: Make sure you have Docker installed on your machine.
  2. Run Mailpit: Open your terminal and run the following command:
    bash
    docker run -d --name mailpit -p 1025:1025 -p 8025:8025 axllent/mailpit
  3. That's it! Mailpit is now running. You can view your email inbox by visiting http://localhost:8025 in your browser.

Configuring Laravel to Use Mailpit

Now, we need to tell Laravel to send its emails to Mailpit instead of a real SMTP server. This is done in your .env file. This file holds all your environment-specific configurations.

Open your .env file and update the MAIL_ variables to look like this:

env
MAIL_MAILER=smtp
MAIL_HOST=localhost
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"
  • MAIL_MAILER=smtp: We're using the standard SMTP protocol.
  • MAIL_HOST=localhost: We're sending it to our own machine, where Mailpit is listening.
  • MAIL_PORT=1025: This is the default port Mailpit uses to catch emails.
  • USERNAME, PASSWORD, ENCRYPTION: We set these to null because Mailpit doesn't require authentication.

For a real production server, you would replace these values with credentials from a service like Amazon SES, Mailgun, or SendGrid. But for local development, this setup is perfect.


2. Creating Mailable Classes and Markdown Email Templates ✍️

The Problem: You could try to build and send an email directly inside a controller method, but it would get messy... fast. Imagine cramming all your HTML, logic for who to send it to, and the subject line all in one place. It's a recipe for unreadable code.

The Solution: Laravel provides "Mailable" classes. These are dedicated PHP classes that represent a specific type of email. Think of them as blueprints for your emails, like WelcomeEmail, OrderConfirmation, or PasswordReset. This keeps all your email-related logic neatly organized in one file.

Creating a Mailable

Let's create a mailable for a new user welcome email. Artisan to the rescue!

bash
php artisan make:mail WelcomeEmail

This command will create a new file at app/Mail/WelcomeEmail.php. Let's take a look inside.

php
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class WelcomeEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Welcome to Our Awesome App!',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            markdown: 'emails.welcome',
        );
    }
}

Markdown for Emails: No More HTML Headaches! 📧

Writing HTML that looks good in every email client (Gmail, Outlook, Apple Mail, etc.) is a notorious pain. They all render things slightly differently.

Laravel solves this with Markdown Email Templates. You write your email content using simple Markdown, and Laravel compiles it into a beautiful, responsive HTML template that has been tested across major email clients.

The content() method in our WelcomeEmail class points to markdown: 'emails.welcome'. This means Laravel will look for a file at resources/views/emails/welcome.blade.php.

Let's create that file and add some content:

resources/views/emails/welcome.blade.php

markdown
<x-mail::message>
# Welcome aboard!

We are so excited to have you.

Thanks,<br>
{{ config('app.name') }}
</x-mail::message>

The <x-mail::message> component provides the standard Laravel email wrapper. Everything inside is just simple Markdown!

Sending the Mail

Now, how do we actually send this email? It's incredibly simple. In your controller (for example, where you handle user registration), you can do this:

php
use App\Mail\WelcomeEmail;
use Illuminate\Support\Facades\Mail;
use App\Models\User;

// ... inside a controller method

$user = User::find(1); // Get the user you want to email

Mail::to($user->email)->send(new WelcomeEmail());

And poof! 💨 If you have Mailpit running, you'll see your beautifully formatted welcome email appear at http://localhost:8025.


3. Introduction to Laravel Notifications (Mail & Database) 🔔

The Problem: What if you want to notify a user about an event in multiple ways? For example, when a user gets a new invoice, you might want to send them an email and show a notification inside the app's UI. You could send the mail and then create a database entry separately, but that's duplicate logic.

The Solution: Laravel Notifications provide a single, fluent API for sending a notification across a variety of "channels," including mail, database, Slack, SMS, and more. You define the notification once and then decide how and where it should be delivered.

Creating a Notification

Let's make a notification for a new invoice.

bash
php artisan make:notification NewInvoiceNotification

This creates a new file at app/Notifications/NewInvoiceNotification.php.

php
<?php

namespace App\Notifications;

// ... other use statements
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class NewInvoiceNotification extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     */
    public function __construct()
    {
        // You can pass data here, like the invoice model
    }

    /**
     * Get the notification's delivery channels.
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail', 'database']; // We want to send this via email AND store it in the DB
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
                    ->line('You have a new invoice!')
                    ->action('View Invoice', url('/invoices/1'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            'message' => 'You have a new invoice for $50.',
            'link' => '/invoices/1'
        ];
    }
}
  • via() method: This is the control center. Here, we specify which channels to use. In this case, we're using both mail and database.
  • toMail() method: This defines what the email version of the notification looks like. It uses a simple, fluent API to build line-by-line emails with calls to action.
  • toArray() method: This defines the data that will be stored in the database as a JSON column. This is what we'll use to render the notification in our UI.

Sending a Notification

Sending a notification is just as easy as sending a mailable. The User model uses the Notifiable trait by default, which gives it a handy notify() method.

php
use App\Notifications\NewInvoiceNotification;

// ... inside a controller method

$user->notify(new NewInvoiceNotification());

When this code runs, Laravel will automatically send the email defined in toMail() and create a new record in the notifications table with the data from toArray(). Two birds, one stone!


4. Displaying Database Notifications in the UI 🖥️

The Problem: Storing notifications in the database is great, but they're useless if the user never sees them. We need to fetch these notifications and display them somewhere, like in a classic notification bell icon in the header.

Setting up the Database

First, we need a table to store the notifications. Laravel has a command for that.

bash
php artisan notifications:table
php artisan migrate

This will create a notifications table with all the necessary columns.

Fetching and Displaying Notifications

The Notifiable trait on your User model gives you access to some very convenient methods for retrieving notifications.

Let's imagine you have a navigation bar in your main layout file. You can fetch and display the user's unread notifications like this.

In a Controller or View Composer:

It's common to fetch this data in a service provider or view composer so it's available on every page, but for simplicity, let's just imagine this logic is in a controller passing data to a view.

php
// In some controller method that renders your main layout
public function dashboard()
{
    $notifications = auth()->user()->unreadNotifications;
    return view('dashboard', ['notifications' => $notifications]);
}

In your Blade View (dashboard.blade.php):

Now you can easily loop through them and display them.

html
<div class="notifications-dropdown">
  @forelse ($notifications as $notification)
    <a href="{{ $notification->data['link'] }}">
      {{ $notification->data['message'] }}
    </a>
  @empty
    <span>No new notifications</span>
  @endforelse
</div>
  • We loop through the $notifications collection.
  • We access the data we stored in the toArray() method using $notification->data['key'].

Marking Notifications as Read

Once a user clicks on a notification, you should probably mark it as read so it doesn't show up in the "unread" list anymore.

You could create a simple route and controller method for this.

Route (routes/web.php):

php
Route::get('/notifications/{notification}/read', 'NotificationController@markAsRead')->name('notifications.read');

Controller (NotificationController.php):

php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    public function markAsRead($notificationId)
    {
        $notification = Auth::user()->notifications()->findOrFail($notificationId);
        $notification->markAsRead();

        return redirect($notification->data['link'] ?? '/');
    }
}

Now, you can update your notification link in the Blade view:

html
<a href="{{ route('notifications.read', ['notification' => $notification->id]) }}">
  {{ $notification->data['message'] }}
</a>

When a user clicks this link, it hits the markAsRead method, marks the notification as read, and then redirects them to the link associated with that notification. A complete, clean, and user-friendly notification system! 🥳

References for Extra Reading

Challenge

Your application needs to notify users upon successful registration. You have been provided with a UserRegistered notification class that receives a User object in its constructor.

Your task is to complete the implementation of this notification class.

  1. Configure the notification to be sent via the mail and database channels.
  2. Implement the toMail() method to create a welcome email. The email must:
    • Have the subject: Welcome to Our Application!
    • Greet the user by name (e.g., Hello, John Doe!).
    • Include the line: Thank you for joining our platform.
    • Have an action button with the text Go to Dashboard that links to the URL /dashboard.
    • End with the line: We are excited to have you!
  3. Implement the toArray() method for the database notification. It should return an array with two keys:
    • message: The string Welcome, {$this->user->name}! Check out your new dashboard.
    • url: The string /dashboard.

Expected result

The completed code should correctly implement the three methods:

  • The via() method must return an array containing the strings 'mail' and 'database'.
  • The toMail() method must return a MailMessage object. It should be built using the fluent API to set the exact subject, greeting (line), a content line, an action button with the specified text and URL, and a final line. The user's name ($this->user->name) should be used for personalization.
  • The toArray() method must return an associative array containing the keys message and url, populated with the specified string values and correctly interpolating the user's name.
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.