Send Slack Notifications From Laravel App

Updated
featured-image.jpg

💡 I included the link to the example repository at the conclusion of this tutorial.

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

#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.jpg

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.jpg

Step 3: Click Incoming Webhooks.

incoming-webhooks.jpg

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

turn-on-incoming-webhhooks.jpg

Step 5: Click add new webhooks to Workspace.

add-new-webhook.jpg

Step 6: Select your channel.

select-channel.jpg

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.jpg

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

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!');
}

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.');
        });
}
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;
}

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/...';
}

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));

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.jpg

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());

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.

Fajarwz's photo
Fajar Windhu Zulfikar

I'm a full-stack web developer who loves to share my software engineering journey and build software solutions to help businesses succeed.

Email me
Ads
  • Full-Stack Laravel: Forum Web App (Complete Guide 2024)
  • Flexible and powerful review system for Laravel, let any model review and be reviewed.

Share

Support

Subscribe

Sign up for my email newsletter and never miss a beat in the world of web development. Stay up-to-date on the latest trends, techniques, and tools. Don't miss out on valuable insights. Subscribe now!

Comments

comments powered by Disqus