Jason Gilmore - September 8, 2020
Sending Slack Notifications from Your Laravel Application

You can now send Slack notifications from Your Laravel application! The DreamFactory team has relied on the Laravel framework for more than five years now, starting with the initial release of our namesake API management platform having been built atop Laravel 5.0. In the years since, our reliance on the framework has only increased; in addition to the DreamFactory platform we’ve built three other fairly complicated applications, two of which are used for internal dashboard purposes and the third being the trial registration and account management site for Genie (https://genie.dreamfactory.com/), our hosted DreamFactory environment.

Like many companies, we’re also heavy Slack users, and rely on automated notifications from a variety of internal and third-party services. As it happens, integrating automated Slack notifications into a Laravel application is an extraordinarily simple process once you understand how the pieces go together. In this blog post I’ll walk you through a real-world example explaining how this is accomplished.

Generate a full-featured,documented, and secure REST API in minutes.

Sign up for our free 14 day hosted trial to learn how.

Generate your No Code REST API now

Configuring Your Laravel Application (Before sending Slack Notifications)

Before you can start sending Slack notifications from your Laravel application we’ll need to install the Slack notification channel package:

$ composer require laravel/slack-notification-channel

You’ll also need to install the “Incoming Webhooks” app in your Slack workspace. By doing so, you’ll be able to generate a unique URL which will be used to send messages to a designated Slack channel.

Incoming WebHooks app

After clicking the “Add to Slack” button, you’ll be taken to the following screen:

Add incoming WebHooks app

Here you’re prompted to choose a channel where the incoming messages will be sent. As you can see in the screenshot, I’ve chosen a channel called #new-trials. If you haven’t yet created the channel, clicking the create a new channel link will cause a modal to open where you can create the destination channel.

Finally, click the “Add Incoming WebHooks Integration” button to generate the unique URL. Once you do, a confirmation notification stating “added an integration to this channel: incoming-webhook” will immediately be sent to the designated Slack channel. Also, the ensuing screen will present your newly generated webhook URL. Copy this URL to the clipboard (it will begin with https://hooks.slack.com), open your Laravel application’s .env file, and assign it to a configuration variable named something like SLACK_NOTIFICATION_WEBHOOK:

SLACK_NOTIFICATION_WEBHOOK="https://hooks.slack.com/services/FEDCBA/H123455ABCDEF"

Generating the Slack Notification

Next we’ll write the code used to send Slack notifications. Fortunately, most of this work is boilerplate, beginning with generation of the notification class which defines the message:

$ php artisan make:notification NewTrial

This will generate a boilerplate notification class geared towards e-mail. You’ll find the class in your project’s app/Notifications directory. We’ll need to make a few modifications to this class in order to support Slack, beginning with referencing the SlackMessage class at the top of the file:

use Illuminate\Notifications\Messages\SlackMessage;

Next, change the via method to look like this:

public function via($notifiable)
{
    return ['slack'];
}

Finally, delete the toMail and toArray methods, and in their place add the following toSlack method:

public function toSlack($notifiable)
{
    return (new SlackMessage)->content('New trial started');
}

When finished, the class will look like this:

<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
class NewTrial extends Notification
{
    use Queueable;
    public function __construct()
    {
        //
    }
    public function via($notifiable)
    {
        return ['slack'];
    }
    public function toSlack($notifiable)
    {
        return (new SlackMessage)->content('hello');
    }
}

Firing the Slack Notification

We’ve generated the Slack notification, however haven’t yet tied the notification into our application logic. There are two ways to do this:

  • Notification Trait: You’ll use the notification trait when you want to send a notification in conjunction an event associated with a specific model instance, such as a trial or product.
  • Notification Facade: You’ll use the notification facade when you want to send multiple notifications associated with a collection, such as multiple trials or products.

For this post we’ll focus on the notification trait. Suppose you want to send a Slack notification whenever a new trial is created. A model named Trial houses the application’s trial-related logic. Open the Trial model and add a reference to the Notifiable class:

use Illuminate\Notifications\Notifiable;

Next add a reference to the Notifiable trait at the top of the class:

class Trial extends Model
{
use Notifiable;
...

Finally, add a new method named routeNotificationForSlack which returns the webhook URL:

public function routeNotificationForSlack($notification)
{
    return env('SLACK_NOTIFICATION_WEBHOOK');
}

You can test the notification by firing up Tinker:

$ php artisan tinker
Psy Shell v0.10.4 (PHP 7.3.21 — cli) by Justin Hileman
>>> $trial = new Trial();
[!] Aliasing 'Trial' to 'App\Trial' for this Tinker session.
=> App\Trial {#3174}
>>> $trial->notify(new App\Notifications\NewTrial());
=> null

Check your Slack channel and you should see a notification like that presented in the below screenshot:

Slack notification

While this notification confirms a successful integration, it isn’t exactly useful. Fortunately we can make some pretty simple modifications to the NewTrial notification class’ toSlack method to add some more context:

public function toSlack($notifiable)
{
    return (new SlackMessage)->content($notifiable->name . " created a new trial");
}

After making these changes, reload Tinker:

$ php artisan tinker
Psy Shell v0.10.4 (PHP 7.3.21 — cli) by Justin Hileman
>>> $trial = new Trial();
[!] Aliasing 'Trial' to 'App\Trial' for this Tinker session.
=> App\Trial {#3174}
>>> $trial->name = "Jason Gilmore";
=> "Jason Gilmore"
>>> $trial->notify(new App\Notifications\NewTrial($trial));

This time, you’ll see a Slack notification stating “Jason Gilmore created a new trial”. We can go even further though! Using a message attachment, we can add even more context:

public function toSlack($notifiable)
{
    return (new SlackMessage)->content($notifiable->name . " created a new trial")
        ->attachment(function ($attachment) use ($notifiable) {
            $attachment->title($notifiable->domain, $notifiable->url)
                       ->fields([
                            'Plan'    => $notifiable->plan,
                            'Country' => $notifiable->country
                        ]);
        });
}

Return to Tinker one more time to test the results:

$ php artisan tinker
Psy Shell v0.10.4 (PHP 7.3.21 — cli) by Justin Hileman
>>> $trial = new Trial();
[!] Aliasing 'Trial' to 'App\Trial' for this Tinker session.
=> App\Trial {#3174}
>>> $trial->name = "Jason Gilmore";
=> "Jason Gilmore"
>>> $trial->domain = "jason.apps.dreamfactory.com";
=> "jason.apps.dreamfactory.com"
>>> $trial->url = "https://jason.apps.dreamfactory.com";
=> "https://jason.apps.dreamfactory.com"
>>> $trial->plan = "Enterprise";
=> "Enterprise"
>>> $trial->country = "US";
=> "US"
>>> $trial->notify(new App\Notifications\NewTrial($trial));
=> null

In a moment you should see a message similar to the following show up in Slack:

Slack confirmation message

Moving Notification Logic Into Your Application

Of course, in production you won’t be executing notifications from Tinker. An ideal location would likely be a trial controller’s store method, because that’s where data associated with a new trial would be persisted to the database. That store method might look something like this:

public function store(TrialStoreRequest $request)
{
    $trial = new Trial();
    $trial->user_id = \Auth::user()->id;
    $trial->name      = $request->name;
    $trial->prefix    = $request->prefix;
    $trial->email     = $request->email;
    $trial->save();
    $trial->notify(new App\Notifications\NewTrial());
    return redirect()->route('trials.index')
        ->with(['status', 'Your trial has been created!']);
}

Generate a full-featured,documented, and secure REST API in minutes.

Sign up for our free 14 day hosted trial to learn how.

Generate your No Code REST API now

Other Useful Laravel Notification Packages

Slack is just one of many available Laravel notification packages. In addition to the notification options described in the Laravel documentation, at the time of this writing there were an additional 52 channels maintained by the Laravel community, including Twitter, Facebook, Twilio, and Microsoft Teams, among others. Head over to the aptly named Laravel Notification Channels website for a complete list.