Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Adding lines conditionally in Laravel's Mail notifications

When working with Mail notifications in Laravel, you’ll often be in a situation where you would want to render something based on some condition.

For instance, you may want to render a line in the Mail notification only when a certain attribute is present/true. How would you do that?

Well, there’s a handy method called when() in the Illuminate\Notifications\Messages\MailMessage class which can be used to do just that.

To use the when() method, all you’ll need is to pass the condition or a boolean value as its first parameter and a Closure that will return the line that you would want to render if the condition is met.

Here’s how you can use it.

<?php

namespace App\Notifications;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Bus\Queueable;

class WelcomeNotification extends Notification implements ShouldQueue
{
    use Queueable, SerializesModels;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function via($notifiable)
    {
        return ['mail'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->greeting('Bonjour '.$this->user->name)
            ->when($this->user->isAdmin, function (MailMessage $mail) { 
                return $mail->line('You have got all the power!');
            )
            ->line('Welcome to our platform.')
            ->line('Thanks')
    }
}

The when() method works the similar way how you would set attributes in Laravel’s resource responses.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?