DEV Community

Fajar Windhu Zulfikar
Fajar Windhu Zulfikar

Posted on • Originally published at fajarwz.com on

Send Slack Notifications From Laravel App

Slack illustration

Slack is a messaging app that generally used by companies. Even Slack call their app as a Digital HQ for companies. Slack is like any other messaging app except it is really designed for business use. It can be used both at desktop and mobile device, making communications easy.

It could be really useful if Laravel can integrate with Slack, and yes it can. Let's get started.

Requirement

We need to install and set the requirements first:

#1 Install Slack notification package via Composer

composer require laravel/slack-notification-channel
Enter fullscreen mode Exit fullscreen mode

#2 We also need to create a Slack App for our team.

Step 1: When you click the link above you will be redirected to Slack API page, for example we can choose From Scratch here.

App from scratch

Step 2: Write the app name that will send the message and pick your workspace. If you haven't the workspace, please create one first. Next, click Create App

Choose workspace

Step 3: Click Incoming Webhooks.

Incoming webhooks

Step 4: Activate the Incoming Webhooks. So the settings below it appear.

Turn on incoming webhooks

Step 5: Click add new webhooks to Workspace.

Add new webhooks

Step 6: Select your channel.

Select channel

Step 7: Now you have the webhook url for your channel, copy it and use it in the route or routeNotificationForSlack in our Laravel app.

Webhook

Generate Notifications

Create a class for our spesific notification with below artisan command, for example we create a InvoicePaid notification. This will generate the class in App\Notifications folder. If we don't have the folder yet, Laravel will create one for us.

php artisan make:notification InvoicePaid
Enter fullscreen mode Exit fullscreen mode

Create Notification format

Use the toSlack method and format the notification

Simple message

We can create a simple notification message like so:

// App\Notifications\InvoicePaid

/**
 * 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!');
}
Enter fullscreen mode Exit fullscreen mode

With Attachments

We can also send attachments to Slack via Laravel. Here is the example:

// App\Notifications\InvoicePaid

/**
 * Get the Slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\SlackMessage
 */
public function toSlack($notifiable)
{
    // ...

    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.');
        });
}
Enter fullscreen mode Exit fullscreen mode

Read also:

Sending Notifications

We can send the notification in two ways: Using Trait and Facade

Using Trait

Using Notifiable trait. For example we can use this in User Model.

<?php

namespace App\Models;

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

class User extends Authenticatable
{
    use Notifiable;
}
Enter fullscreen mode Exit fullscreen mode

Specify the route notification in the model for our notification that we get in the Point 2 - Step 7 in the Requirement section we previously do.

// App\Models\User

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

Use the notify() method that is provided by this trait to send the notification.

use App\Models\User;
use App\Notifications\InvoicePaid;

$user = new User;

$user->notify(new InvoicePaid($invoice));
Enter fullscreen mode Exit fullscreen mode

Here is an example display when the integration is successful and the notification sent successfully to Slack. Slack will categorize our notification system as an "App".

Result example

Using The Notification Facade

Another way is using Notification facade. We can use this in any class. Specify the route or the webhook.

use Illuminate\Support\Facades\Notification;

Notification::route('slack', 'https://hooks.slack.com/services/...') //you can put the route in .env too
    ->notify(new InvoicePaid());
Enter fullscreen mode Exit fullscreen mode

Conclusions

That's it, it's easy to send notification to Slack with Laravel. First install the package required, create a webhook in Slack, and send the notification via one of the two ways: Trait or Facade.

A repo for this example can be found here fajarwz/blog-laravel-slack.

There is also a known package for this package alternative: spatie/laravel-slack-alerts.

Any thought? Please comment below đŸ‘‡, thank you!

Further Reading

Slack Notifications - Laravel Docs

Subscribe

Subscribe @fajarwz Medium for more content.

Top comments (0)