Oh Dear! monitors your entire website, not just the homepage. You'll get a notification as soon as your website is down, a monthly uptime report, a warning a few days before your SSL certificate expires and much more! Start your free 10 day trial now!

Notification specific routing in Laravel 5.6

Original – by Freek Van der Herten – 2 minute read

Laravel has a very powerful notification system. From the docs:

In addition to support for sending email, Laravel provides support for sending notifications across a variety of delivery channels, including mail, SMS (via Nexmo), and Slack. Notifications may also be stored in a database so they may be displayed in your web interface.

Summarized you can send a Notification to a Notifiable via a certain channel. A notifiable can be any class that uses the Notifiable trait, for example a user. A good example of a channel is Slack.

In Laravel 5.4 and 5.5 this is how you can specify the slack webhook to be used when sending a user a notification.

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Route notifications for the Slack channel.
     *
     * @return string
     */
    public function routeNotificationForSlack()
    {
        return $this->slack_webhook_url;
    }
}

The problem is that there is no way to send a a specific notification to a specific Slack webhook.

In Laravel 5.6 this is solved by using the notification that's being passed to the routing method on the notifiable.

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Route notifications for the Slack channel.
     *
     * @return string
     */
     public function routeNotificationForSlack($notification)
     {
          if ($notification instanceof MySpecialSnowflakeNotification) {
               return $this->alternative_slack_webhook;
          }
     
          return $this->slack_webhook;
     }
}

If you want to know some more new Laravel 5.6 features, be sure to watch Taylor's talk at Laracon Online this Wednesday.

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.