Understanding Laravel Notifications

Words
363
Reading
2 min
Listen
Play
9y

What Will I Learn?

In this tutorial, you are going to

  • Understand Laravel Notifications
  • Understand Notification Channels
  • Use Laravel Notification in a sample application

Requirements

To follow along in this tutorial, you need to be conversant with the Laravel framework

Difficulty

  • Intermediate

Tutorial Contents

If you've been around the Laravel community for a while, you'll understand that Laravel components are named logically. Notifications are a way to report that an activity has occurred. Laravel notifications gives us the ability to do this except that it provides more power.

Imagine that a user just registered. We need to

  • Fire a mail to notify the user
  • Send an SMS to welcome the user to the platform
  • Send a slack notification to notify us of the new activity.

The good news is with laravel, we can do this in one class, a Notification class.

Lets create our class.

Like many other things in Laravel, we can create a notification using artisan

$ php artisan make:notification UserSignedUp

A new file will be created at app/notifications/UserSignedUp.php and it should contain this;

<?php

namespace App\Notifications;

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

class UserSignedUp 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 [
            //
        ];
    }
}
  • You may pass any properties you wish to use into the __construct() method.

  • The via() method returns an array of notification channels. Notification channels are the the various medium with which laravel notifies users. e,g ['mail'] means only a mail notification will be sent. At the time of writing this tutorial, laravel notifications support these channels;

  • mail

  • nexmo

  • broadcast

  • database
    -array

Channels are implemented by appending the channel name to a to string. For instance, a database channel would be implemented as such


<?php

class xxxxx {

public function toDatabase($notifiable){

}
}

As you can see, a $notifiable property us available for use. Anything can be a notifiable. A notifiable is any class that implements a notification. Hope that makes sense.

In the example above, a mail notification has been implemented and has been registered in the via method. Let's tweak it a little.

<?php

namespace App\Notifications;

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

class UserSignedUp extends Notification
{
    use Queueable;

    private $user;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * 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("Hello {$this->user->firstname}, welcome to our website. Confirm your email address to continue")
                    ->action('Confirm Email', 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 [
            //
        ];
    }
}

Let's send our notification. There are two ways to send notifications.

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

$user->notify(new UserSignedUp($user));

To use this method, your model (in this case User.php) must use a Notifiable trait.

  1. Using the Notifications Facade
Notification::send(Auth::user(), new UserSignedUp(Auth::user()));

Feel free to try out other notification channels.

I hope i've been able to get you up and running with Laravel Notifications.



Posted on Utopian.io - Rewarding Open Source Contributors