Laravel Notification

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

The various channels that notification can be sent are:

  • Mail
  • SMS
  • Slack and others

Create Laravel Notification

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

Run the command below to create notification class:

php artisan make:notification NewItem

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

<?php

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

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

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 above code.

Send Laravel Notification

Here we will discuss about methods for sending notification to the user. Basically, there are two methods i.e. notify of Notifiable trait and Notification facade.

This is how you activate notification 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, user can also send notification via notification facade. If notification is to be sent to 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 notification via mail then configure toMail method. In this method, user can write their own 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 notification via email.

Slack Notification

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

composer require laravel/slack-notification-channel

Like in mail, you should also configure slack. For configuring slack, you should at first define toSlack(). Slack notification supports text as well as attachments. Here is an 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

User needs to define routeNotificationForSlack method to route notification to proper location. Now to get notification got to https://{yourteam}.slack.com/apps. Choose “Incoming Webhook” type. Now copy 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, lets discuss about database notification. Basically what it does is, it stores notification information in database. It stores notification type and also custom JSON notification data.

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

php artisan notifications:table

php artisan migrate

Migrate command creates a migration file for notification table. After that, create toDatabase() or toArray() method such that it returns plain PHP array. The, store the returned array in data column of 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 inbuilt method. The Illuminate\Notifications\Notifiable trait has eloquent relationship that returns notification for an entity. Notification are in order of descending order by default.

First of all,to fetch notification 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 notifications that are unread. Here is an example for that process:

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

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

$user->unreadNotifications->markAsRead();

Lastly, lets look at how to delete database notification:

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

Conclusion

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

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


Leave a Comment