Laravel Notifications – Easily send quick updates through Slack, SMS, Email, and more

Published on by

Laravel Notifications – Easily send quick updates through Slack, SMS, Email, and more image

Laravel Notifications is an all new feature coming to Laravel 5.3 that allows you to make quick notification updates through services like Slack, SMS, Email, and more.

Let’s see how easy it is to build and send a notification using this new feature:

class NewPost extends \Illuminate\Notifications\Notification
{
public function __construct($post)
{
$this->post = $post;
}
 
public function via($notifiable)
{
return ['database'];
}
 
public function toArray($notifiable)
{
return [
'message' => 'A new post was published on Laravel News.',
'action' => url($this->post->slug)
];
}
}

All you need to do now is to send the notification to the selected users:

$user->notify(new NewPost($post));

Creating Notifications

Laravel 5.3 ships with a new console command for creating notifications:

php artisan make:notification NewPost

This will create a new class in app/Notifications, each notification class contains a via() method as well as different methods for building notifications for different channels.

Using the via() method you can specifying the channels you’d like this particular notification to be sent through, check this example for the official documentation website:

public function via($notifiable)
{
return $notifiable->prefers_sms ? ['sms'] : ['mail', 'database'];
}

The via method receives a $notifiable instance, which is the model you’re sending the notification to, in most cases it’ll be the user model but it’s not limited to that.

Available channels are: mail, nexmo, database, broadcast, and slack.

Formatting Email Notifications

You can format how notifications are sent through different channels, for instance, let’s take a look at formatting a mail notification:

public function toMail($notifiable)
{
return (new MailMessage)
->subject('New Post!')
->line('A new post was published on Laravel News!')
->action('Read Post', url($this->post->slug))
->line('Please don\'t forget to share.');
}

This will create a mail message using a nice built-in responsive template that you can publish using the vendor:publish console command.

The notification system will automatically look for an email property in your model, however, you can customise this behaviour by defining a routeNotificationForMail in your Model and return the email address this Model will be contacted on.

Formatting Nexmo SMS Notifications

Same as in the case of an email notification, you need to define a toNexmo method in your notification class:

public function toNexmo($notifiable)
{
return (new NexmoMessage)
->from(123456789)
->content('New post on Laravel News!');
}

In the case of Nexmo notifications, laravel will look for a phone_number property in the model. You can override that by defining a routeNotificationForNexmo method.

You can set a global from number in your Nexmo configuration file, that way you won’t have to provide a from number in each notification.

Formatting Database Notifications

To Format a database notification you may define a toDatabase method:

public function toDatabase($notifiable)
{
return new DatabaseMessage([
'message' => 'A new post was published on Laravel News.',
'action' => url($this->post->slug)
]);
}

To start using the database channel you may read the full documentation on the official website.

Sending Notifications

You can send notifications using the notify() method on your model, this method exists on the Notifiable trait which you’ll need to add to your Model.

$user->notify(new NewPost($post));

You can also use the Notification facade, this will allow you to send notifications to multiple notifiables at the same time:

Notification::send(User::all(), new NewPost($post));

Queueing Notifications

You can easily queue sending notifications by using the ShouldQueue interface on the Notification class and including the Queueable trait.

<?php
 
namespace App\Notifications;
 
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
 
class NewPost extends Notification implements ShouldQueue
{
use Queueable;
}
Mohamed Said photo

Web Developer and Laravel Core Contributor

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Forge
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
Bacancy - Staff Augmentation logo

Bacancy - Staff Augmentation

Leave your web app development hustles to the leading IT Staff Augmentation Service Providers. Choose from an extensive pool of 1050+ developers and give yourself the sigh of success you deserve with Bacancy. Get In Touch Today!

Bacancy - Staff Augmentation
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Add Architecture Tests to Saloon API Integrations with Lawman image

Add Architecture Tests to Saloon API Integrations with Lawman

Read article
Protect Routes with JWT Tokens Using This Package for Laravel image

Protect Routes with JWT Tokens Using This Package for Laravel

Read article
Increment a Rate Limiter by a Custom Amount in Laravel 10.46 image

Increment a Rate Limiter by a Custom Amount in Laravel 10.46

Read article
Add Kanban Boards to Your Laravel App in Seconds image

Add Kanban Boards to Your Laravel App in Seconds

Read article
October CMS v3.6 Ships Today, Full of New Features image

October CMS v3.6 Ships Today, Full of New Features

Read article
Laracon EU Videos are now out image

Laracon EU Videos are now out

Read article