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.

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
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
The Inertia.js v2 Beta is Here image

The Inertia.js v2 Beta is Here

Read article
Mastering Laravel, No Compromises, and SourceDive with Joel Clermont image

Mastering Laravel, No Compromises, and SourceDive with Joel Clermont

Read article
Now you can install PHP and the Laravel installer with a single command image

Now you can install PHP and the Laravel installer with a single command

Read article
WireSpy is a Sleek New Debug Bar for Laravel Livewire image

WireSpy is a Sleek New Debug Bar for Laravel Livewire

Read article
The Laracon AU schedule is now live image

The Laracon AU schedule is now live

Read article
Supercharge PhpStorm with Laravel Idea image

Supercharge PhpStorm with Laravel Idea

Read article