Blog Detail

15

Dec
How to Send Slack Notifications from Your Laravel App cover image

arrow_back How to Send Slack Notifications from Your Laravel App

Slack is a messaging app for businesses that connects people to the information that they need. Slack can replace email, text messaging, and instant messaging for your team, and keep all those communication styles together in one app. With both desktop and mobile versions, Slack can help your team collaborate and coordinate their work no matter where they are.

So Laravel comes up with a notifications feature that allows you to send short updates through various services like Slack, SMS (Nexmo), Email, etc., and guys it is quite wonderful.

Installation

For sending notifications via Slack, you must install the Slack notification channel via Composer, Just run this command:

composer require laravel/slack-notification-channel

You will also need to create a Slack App for your team. After creating the App, you should configure an “Incoming Webhook” for the workspace. Slack will then provide you with a webhook URL that you may use when routing Slack notifications.

Formatting Slack Notifications

If a notification supports being sent as a Slack message, you should define a toSlack method on the notification class. This method will receive a $notifiable entity and should return an Illuminate\Notifications\Messages\SlackMessage instance. Slack messages may contain text content as well as an “attachment” that formats additional text or an array of fields. Let’s take a look at a basic toSlack example:

/**
 * Get the Slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\SlackMessage
 */
public function toSlack($notifiable)
{
    return (new SlackMessage)
                ->content('One of your invoices has been paid!');
}

Customizing The Sender & Recipient

You may use the from and to methods to customize the sender and recipient. The from method accepts a username and emoji identifier, while the to method accepts a channel or username:

/**
 * Get the Slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\SlackMessage
 */
public function toSlack($notifiable)
{
    return (new SlackMessage)
                ->from('Ghost', ':ghost:')
                ->to('#bots')
                ->content('This will be sent to #bots');
}

You may also use an image as your from “logo” instead of an emoji:

/**
 * Get the Slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\SlackMessage
 */
public function toSlack($notifiable)
{
    return (new SlackMessage)
                ->from('Laravel')
                ->image('https://laravel.com/img/favicon/favicon.ico')
                ->content('This will display the Laravel logo next to the message');
}

Slack Attachments

You may also add “attachments” to Slack messages. Attachments provide richer formatting options than simple text messages. In this example, we will send an error notification about an exception that occurred in an application, including a link to view more details about the exception:

/**
 * Get the Slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\SlackMessage
 */
public function toSlack($notifiable)
{
    $url = url('/exceptions/'.$this->exception->id);

    return (new SlackMessage)
                ->error()
                ->content('Whoops! Something went wrong.')
                ->attachment(function ($attachment) use ($url) {
                    $attachment->title('Exception: File Not Found', $url)
                               ->content('File [background.jpg] was not found.');
                });
}

Attachments also allow you to specify an array of data that should be presented to the user.

Routing Slack Notifications

To route Slack notifications to the proper Slack team and channel, define a routeNotificationForSlack method on your notifiable entity. This should return the webhook URL to which the notification should be delivered. Webhook URLs may be generated by adding an “Incoming Webhook” service to your Slack team:

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Route notifications for the Slack channel.
     *
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return string
     */
    public function routeNotificationForSlack($notification)
    {
        return 'https://hooks.slack.com/services/...';
    }
}

Laravel also allows you to send notifications in a locale other than the HTTP request’s current locale, and will even remember this locale if the notification is queued. For more details, you can visit its documentation & source code on Github.

Published at : 15-12-2021

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project