DEV Community

Freek Van der Herten
Freek Van der Herten

Posted on • Originally published at freek.dev on

★ Notification specific routing in Laravel 5.6

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.

Top comments (0)