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.

Join 9,500+ smart developers

Get my monthly newsletter with what I learn from running Spatie, building Oh Dear, and maintaining 300+ open source packages. Practical takes on Laravel, PHP, and AI that you can actually use.

"Freek publishes a super resourceful and practical newsletter. A must for anyone in the Laravel space"

Joey Kudish — Shipping with AI as a teammate

No spam. Unsubscribe anytime. You can also follow me on X.

Found something interesting to share? Submit a link to the community section.