Laravel Notifications – The Ultimate Guide

Laravel Notifications - The Ultimate Guide

The Laravel Notification system allows us to send notifications to users through different channels. In this post, we will look at Laravel Notifications, the most beautiful way of handling notifications for your web application.

What are Notifications?

During web application development, you often need to notify users about different changes or actions. It could be either using the email notifications when an order status changes or sending slack messages when a background task complete within your application. Usually, these messages are short and just provide insight into the state changes.

Laravel provides mailables which can be used to send emails, these emails are long with custom markup styling but we can not be sent through different channels. Laravel Notifications solves our this problem, by providing an elegant and fun way to send notifications to users.

Laravel Notifications Channels

The whole beauty of Laravel Notifications is that it allows you to choose from different notifications channels through which your notifications will be delivered. Let’s go through the different notifications channels currently supported by Laravel Framework.

  • Mail : The notifications will be send in the form of email to users.
  • SMS : Users will revieve notifications on their mobile phones.
  • Database : This option allows you to save notifications into the database, which you can show to users in your own way.
  • Slack : This option allows us to send notification messages to Slack channel.

In this post, we will be looking at mail, database and Slack notifications as these are the most widely used channels.

Installing Laravel Application

To start with this tutorial, we will quickly install Laravel using the Composer command like below.

composer create-project laravel/laravel LaraNotifications
For a details guide on installing Laravel, please follow our guide for Laravel Installation.

Once you have Laravel application ready, open the .env file and update your database settings in it.

Creating Laravel Notification

Laravel Notifications are easy to use as it will generate a single class for each notification. In this class, you can describe how you want to deliver the notification to users.

To create a new notification class, run the below command in your command line terminal.

php artisan make:notification NewUser

Above command will create a new file located at app\Notifications\NewUser.php with the following file content.

namespace App\Notifications;

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

class NewUser extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Notice the via method in the above class, this is where you can specify how you want the user to be notified. In the above class, its declared that we want to use the email notification.

return ['mail'];

Since we want to use the email delivery channel, it will fire the toMail() method.

Firing Laravel Notification

To enable Laravel notifications for our User model, we must use the use Illuminate\Notifications\Notifiable; trait like below.

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
}

Laravel provide User model out of the box, thus it is using the notifications trait already. If you want to enable notifications for your own custom model such as Customer or Admin then you must use the Notifiable trait in your model class.

After adding the trait you can simply send the notification to a user like below.

$user->notify(new App\Notifications\NewUser);

Now $user will recieve the NewUser notification.

You can also use the Notification facade to send notifications like below.

Notification::send($user, new App\Notifications\NewUser);

Before sending email notification, we will change our toMail() method with our custom message.

/**
 * Get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
                ->line('Welcome to our application, you now can use our application.')
                ->action('Visit Your Account', url('/'))
                ->line('Thank you for using our application!');
}

So far we have seen how we can generate a notification class and use it to send a notification to a user through mail channel. In the coming sections, we will look at how we can set up the notifications for the database and Slack.

Database Notifications

The database notifications are stored in your database table. This table contains information such as the custom JSON message you want to send.

Before using the database notifications, we have to create a new table for notification. Don’t worry, Laravel got you covered with the below command.

php artisan notifications:table
php artisan migrate

The above commands will create a new migration file for the notifications table and create the table in your database.

As I mentioned earlier, for mail notification we have to use the toMail() method. For database notifications, you need to define either toDatabase() or toArray() method and it should return a plain PHP array. The returned array will be stored in the data column of the notifications table.

As we have toArray() method in our above class, we will use that and modify it. After making changes for a database, our notification class will look like below.

namespace App\Notifications;

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

class NewUser extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail', 'database'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('Welcome to our application, you now can use our application.')
                    ->action('Visit Your Account', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'message'   =>  'Account registered successfully.'
        ];
    }
}

Now our above class, we send the notification to both mail and database channels.

Displaying Database Notifications

Laravel provides couple of methods to access and delete the database notifications. Our User model is using the Notifiable trait, which includes an Eloquent relationship that return the notifications for a user.

To fetch notification for a user, simply use the notifications relationship.

$user = auth()->user();
foreach ($user->unreadNotifications as $notification) {
    echo $notification->type;
}

To get all unread notifications you can get them like below.

foreach ($user->unreadNotifications as $notification) {
    //
}

To mark a notification as read.

foreach ($user->unreadNotifications as $notification) {
    $notification->markAsRead();
}

To mark all notifications as read, use the markAsRead() method directly on the collection of notifications.

$user->unreadNotifications->markAsRead();

To delete all notifications for a particular User model, use it like below.

$user->notifications()->delete();

Slack Notifications

To use Slack notifications, firstly you have to include the Guzzle HTTP into your application.

composer require guzzlehttp/guzzle

Next, we will update our notification class NewUser and chage the via() method like below.

/**
 * Get the notification's delivery channels.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function via($notifiable)
{
    return ['mail', 'database', 'slack'];
}

Now our notification class is using three delivery channels, to keep it simple I am using one class for all three channels. In my professional projects, I prefer to create multiple classes for each delivery channel.

Next, we will add the toSlack() method like below.

/**
 * Get the Slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return SlackMessage
 */
public function toSlack($notifiable)
{
    return (new SlackMessage)
        ->content('Account Registered successfully.');
}

Setting Incoming Hook

Now to receive Slack notification go to https://{yourteam}.slack.com/apps. Choose the “Incoming Webhook” type and add a new configuration.

Copy the Webhook URL and head back to your Laravel application.

To route Slack notification, we need to define the routeNotificationForSlack() method in our User model class.

 /**
 * Route notifications for the Slack channel.
 *
 * @param  \Illuminate\Notifications\Notification  $notification
 * @return string
 */
public function routeNotificationForSlack($notification)
{
    return 'your_webhook_url.';
}

To learn more about the various options available for Slack notifications, please read through the Official Laravel Documentation.

Final Words

In this tutorial, we created a Laravel notification system and learned, how to send an email, database and Slack notifications in Laravel applications. If you have any query feel free to comment below and subscribe to our blog for more Laravel tutorials.

4 comments on “Laravel Notifications – The Ultimate Guide

  1. what is this here you using $user = auth()->user();
    this is new thing for me.

    i mostly use’s like this Auth::user();
    so tell me difference between the line you typed.Thanks
    HAPPY CODING.

  2. Hi, I noticed you wrote:

    As we have toJson() method in our above class, we will use that and modify it.

    But then the example just below shows a “toArray” implementation. Is it a typo or am I don’t understanding this?
    Tks

Leave a Reply

Your email address will not be published. Required fields are marked *

*

When sharing a code snippet please wrap you code with pre tag and add a class code-block to it like below.
<pre class="code-block">you code here</pre>

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Your little help will keep this site alive and help us to produce quality content for you.