Laravel Notification

As Laravel is a heavy framework, it provides support for sending notifications across various channels. Here in this session, we will take a look at the creation and handling of notifications.

The various channels through which notifications can be sent are:

  • Mail
  • SMS
  • Slack and others

Create Laravel Notification

Laravel creates a single class for each notification which makes it easy to use. These classes are inside the app/notification. Users can configure this class to describe how to send notifications.

Run the command below to create a notification class:

php artisan make:notification NewItem

Above command creates NewItem.php inside app/notification. Its structure looks like this:

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

We can configure via method to specify by what means the user wants to notify clients. It is set to mail by default as shown in the above code.

Send Laravel Notification

Here we will discuss methods for sending notifications to the user. There are two methods i.e. notify of Notifiable trait and Notification facade.

This is how you activate notifications in a model.

<?php

namespace App;

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

class Client extends Authenticatable
{
    use Notifiable;
}

After configuration, you can send notification by:

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

Alternatively, users can also send notifications via the notification facade. If notification is to be sent to a large number of people then it comes in handy. Example:

Notification::send($users, new NewItem($item));

Mail Notification

If the mail that you are trying to send a notification via mail then configure toMail the method. In this method, user can write their custom message as well.

/**
 * 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 can now use our application.')
                ->action('Visit Your Account', url('/'))
                ->line('Thank you for using our application!');
}

This is how we send notifications via email.

Slack Notification

At first, you have to install a notification channel to send notifications via Slack. You can install it by:

composer require laravel/slack-notification-channel

Like in the mail, you should also configure Slack. For configuring Slack, you should first define toSlack(). Slack notification supports text as well as attachments. Here is a basic example of Slack:

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

Route Incoming Hooks

The user needs to define the routeNotificationForSlack method to route notifications to the proper location. Now to get a notification go to https://{yourteam}.slack.com/apps. Choose the “Incoming Webhook” type. Now copy the webhook URL and do the following:

<?php

namespace App;

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

class Client extends Authenticatable
{
    use Notifiable;

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

Database Notification

At last, let’s discuss about database notification. Basically what it does is store notification information in the database. It stores notification type and also custom JSON notification data.

First of all, create a database table for storing notifications. You can use the following command:

php artisan notifications:table

php artisan migrate

Migrate command creates a migration file for the notification table. After that, create a toDatabase() or toArray() method such that it returns a plain PHP array. Then, store the returned array in the data column of the notification table.

At last, configure toArray() or toDatabase() so that it looks like this:

namespace App\Notifications;

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

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

Access Database Notification

For accessing database notification Laravel has an inbuilt method. The Illuminate\Notifications\Notifiable trait has an eloquent relationship that returns notification for an entity. Notifications are in order of descending order by default.

First of all, to fetch notifications use the following code:

$user = App\User::find(1);

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

Sometimes a user may only want to fetch unread notifications. Here is an example of that process:

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

There is also a method available to mark notifications as read. Here is an example:

$user->unreadNotifications->markAsRead();

Lastly, let’s look at how to delete database notifications:

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

Conclusion

These three methods are among the best methods for sending notifications. Hence, please go through all these methods and share them with others if you like them.

Click here to check our other tutorials. You can also go through official Laravel documentation to know more about other methods.

Asmit Nepali, a Full Stack Developer, holds a Software Engineering degree from Gandaki College of Engineering and Science. Proficient in PHP Laravel, Vue.js, MySQL, Tailwind, Figma, and Git, he possesses a robust technical skill set.

Leave a Comment