Laravel Notifications — Admin and dynamic recipients

Photo by Jerry Kiesewetter

Laravel notifications introduced in 5.3 have been a godsend. Simply get the user you want to send a notification to and

$user->notify(); 

Bam! It’s sent.

But what about when you have to send an email to the site administrator? Sure, maybe they are a user and we can look them up. Or perhaps create some sort of admin user that won’t be used to login but only receive these messages. Doesn’t that seem a bit messy?

Of course if you’re only using email you could still just use Laravel’s Mail class, but this still requires a good amount of change later on if we do decide admin should also receive SMS.

Consider making “Recipients”

For my newer projects, I’ve been creating “Recipient” classes specifically to interact with notifications and it’s been a clean way to handle this problem.

In my Laravel “/app” directory I have a sub directory named “Recipients” which holds any of these exceptions that may receive an email (Or some other type of notification).

Each Recipient class extends my abstract “Recipient” parent class like in the examples below:

Our parent class:

<?php
//app/Recipients/Recipient.php
namespace App\Recipients;

use Illuminate\Notifications\Notifiable;

abstract class Recipient{

use Notifiable;

protected $email;

}

And our AdminRecipient class:

<?php
//app/Recipients/AdminRecipient.php
namespace App\Recipients;

class AdminRecipient extends Recipient{

public function __construct()
{
$this->email = env(’ADMIN_EMAIL’);
}

}

Of course in this case, the admin email is passed via an environment variable but this could use any method such as a fixed value or browsing the database for a setting field.

Now sending the site administrator(s) a notification is a piece of cake:

$recipient = new AdminRecipient();
$recipient->notify(new AdminAlert());

If we wanted to, we could also make a dynamic recipient. A class that takes an email (or other contact info) on the fly:

<?php
//app/Recipients/DynamicRecipient.php
namespace App\Recipients;

class DynamicRecipient extends Recipient {

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

}

Giving us a simple and clean way to pass data directly into a notification:

$recipient = new DynamicRecipient('email@email.com');
$recipient->notify(new GeneralNotification());