Laravel Notifications – The Ultimate Guide 2024

The Laravel Framework offers a Notification system that enables sending notifications to users using various channels. This tutorial explores Laravel Notifications, which provides an aesthetically pleasing method of managing notifications for your web application.

What are Notifications?

When building PHP Laravel applications, developers often need to notify users of different changes or actions within their web applications. These notifications could be in the form of emails when an order status changes or Slack messages when a background task completes. Typically, these messages are short and provide information about state changes.

While Laravel provides “Mailables” to send emails with custom markup styling, they cannot be sent through different channels. This is where Laravel Notifications come in handy. It offers an elegant and user-friendly way to send notifications to users through various channels, such as email, SMS, or Slack.

Laravel Notifications Channels

Laravel Notifications offer developers the flexibility to choose from various notification channels through which notifications can be delivered to users. Let’s explore the different notification channels currently supported by the Laravel Framework.

Mail: This notification channel allows developers to send notifications to users in the form of emails. Users will receive an email notification when an event or action occurs within the web application.

SMS: This channel enables developers to send notifications to users on their mobile phones via text messages. This is an effective way to reach users who are not always online but have their phones with them.

Database: This option allows you to save notifications in the database, which can be displayed to users in their preferred format. This is useful for applications that require notification history or that need to store notifications for a long time.

Slack: With this channel, developers can send notification messages to a Slack channel. This is helpful for teams who use Slack for communication and collaboration.

This tutorial will focus on mail, database, and Slack notification channels as they are widely used by developers.

Step 1: Install Laravel Application

To get started with this tutorial, we will quickly install Laravel using the Composer command below:

composer create-project laravel/laravel LaraNotifications

Step 2: Setup Database Connection

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

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laranotifications
DB_USERNAME=root
DB_PASSWORD=12345

Step 4: Create Notification In Laravel

Laravel Notifications are user-friendly and straightforward to use. It generates a single class for each notification, which developers can customize to define how they want to deliver the notification to users.

To create a new notification class, run the following command in the command line terminal:

php artisan make:notification NewUser

The 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 [
            //
        ];
    }
}

Please note the via method in the above class definition, this is where you can specify how you want the user to be notified i.e via Email or SMS. In the above class, it’s declared that we want to use Email notifications.

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 the below:

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;
}

Laravel comes with a built-in User model that includes the notifications trait by default. If you want to enable notifications for your custom models, such as Customer or Admin, you must use the Notifiable trait in your model class like in the code above.

After adding the Notifiable trait to a custom model, you can easily send notifications to Users using the following syntax:

$user->notify(new App\Notifications\NewUser);
$user->notify(new ExampleNotification($message)); // use this

Now $user will receive the NewUser notification.

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

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

Before sending an 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!');
}

Up to this point, we have discussed how to generate a notification class and use it to send notifications to users through the mail channel. In the following sections, we will explore how to set up notifications for the database and Slack channels.


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 database table for storing notifications. Please use the following PHP artisan commands to create a new database migration file:

php artisan notifications:table
php artisan migrate

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

As previously mentioned, to send mail notifications, we must use the toMail() method. However, for database notifications, we must define either the toDatabase() or toArray() method, which must return a plain PHP array. This array will be stored in the data column of the notifications table.

We need to modify the toArray() method in our notification class. After making the necessary changes, the notification class for the database channel will look like the following:

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.'
        ];
    }
}

Displaying Database Notifications

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

To fetch notifications for a user, simply use the notifications relationship:

$user = auth()->user();

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

To get all the “unread notifications”, you can use the following code snippet:

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

To mark unread notifications as read one by one, use the following code in a foreach loop:

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

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

$user->unreadNotifications->markAsRead();

To delete all the notifications for a particular User model, we can use the following code:

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

Slack Notifications

To use Slack notifications, first, we need to include the Guzzle HTTP package in our Laravel application using Composer.

composer require guzzlehttp/guzzle

Next, we need to update our notification class NewUser and change the via() method like the below:

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

Next, we will add the toSlack() method like the 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 in Slack

To receive Slack notifications, 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 notifications, 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 for Laravel Slack Notifications.


In this blog post, we discussed how to set up Laravel Notifications for different channels, including mail, database, and Slack. We also explored how to customize Laravel Notification Messages and mark notifications as read.

Leave a Comment