Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free 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.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month 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.

Comments

What are your thoughts on "Notification specific routing in Laravel 5.6"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.