Support the ongoing development of Laravel.io →

Receive Slack Notifications from your Laravel App with a 10-minute Setup

22 Sep, 2024 5 min read 182 views

Photo by Getty Images on Unsplash

In the previous article, I introduced a Backpack's new Menu Dropdown Column component which I use for my e-commerce admin panel. Today, I will talk about a Laravel feature I use to receive Order Notifications. Whenever an order comes, my team is notified to ship it ASAP. You can assume the importance of receiving quick notifications for such events.

I also use it in:

  • Log Manager: To get notified of website error events ASAP.
  • Backup Manager: To get notified if the backup fails.
  • To receive notification if some Queued Job/Background running task fails.
  • To receive Daily reports.
  • And... Many events(Getting live updates fasten up the process)

Laravel officially supports it. Thus, many laravel packages supports it too.

In this tutorial, I assume you have a basic knowledge of Laravel Notifications and you know about Slack. Slack is a messaging app designed for business use. It can be used on desktop and mobile devices, making communications easy.

Create a Slack App

First, we need a Slack account to create a new #Channel & our Slack App. The following steps will help you to create one for your Laravel app.

Steps Screenshot
1. Sign in on Slack & Start with free plan. 1
2. Go to https://api.slack.com/apps. Click on Create an app & select From scratch as we are building a simple app. 2
3. Next, you will be asked to create or select a workspace. Just name it. 3
4. After workspace, You can Create an App for that. 4
5. Name your Slack App & choose the workspace. 5
6. Next, click on Incoming Webhooks. 6
7. Activate! Incoming Webhooks & Click "Add New Webhook to Workspace". 7
8. Choose a channel where this webhook will send messages. 8
9. Final Step! Navigate to OAuth & Permissions. Add scopes such as chat:write, incoming-webhook ,chat:write.public and copy the OAuth Token. 9

Done! You need to paste the Token & Webhook URL into Your Laravel App to send notifications.

Package Installation

Install the official Slack Notification Channel package:

composer require laravel/slack-notification-channel

Paste the Webhook & Oauth Token in your Laravel configuration.

Use them within the slack configuration array in config/services.php. Your Laravel App is now ready to send notifications.

'slack' => [
    'notifications' => [
        'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
        'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
    ],
],

Send Notifications

In general, multiple channels are created depending on the type of notification. I created two more channels & two webhooks for each channel. For example: #orders, #errors-logs, #backup-logs.

Use webhook URL in the packages.

Each package that supports Slack notifications comes with a config file where we only need to configure the webhook URL.

  • For Backup Manager, paste the webhook URL in config/backup.php & enable the channel for package's notification class:
'notifications' => [
-    \Spatie\Backup\Notifications\Notifications\BackupHasFailedNotification::class => ['mail'],
+    \Spatie\Backup\Notifications\Notifications\BackupHasFailedNotification::class => ['slack'],
    ...            
    ],

'slack' => [
+   'webhook_url' => env('SLACK_BOT_BACKUP_WEBHOOK_URL'),           
    ...
],
  • For Log Manager, paste the webhook URL in config/logging.php to enable it:
'slack' => [
+   'url' => env('SLACK_BOT_ERROR_LOG_WEBHOOK_URL'),   
    ...
],

Thats it! These packages will be sending the notifications on their configured events.🔔

Creating a Custom Notification

Now let's talk about creating Notification as per our needs.

  1. Command to create a notification class:
php artisan make:notification OrderNotification
  1. Add a toSlack() method and format the notification:
use Illuminate\Notifications\Slack\SlackMessage;

public function toSlack($notifiable)
{
    return (new SlackMessage)
            ->to("#orders") // set the channel
            ->text('Check & update order status.')
            ->headerBlock('#'.$this->order->id.' Order Received🎉');
}

You can find a set of blocks here for formatting beautiful Slack notifications. You can also give action choices to the user with actionsBlock() available here.

  1. Enable slack delivery channel for the notification:
public function via($notifiable)
{
-    return ['mail'];
+    return ['mail', 'slack'];
}

Tip: You can turn channels on/off for each Notification by conditionally altering the array.

Done! Our Notification is ready to send on Slack.

For a better understanding of Notificaton::class, You can check this Gist. I use it to send E-mail & SMS to user and receive Slack notification when an order gets placed.

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

  1. 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;
}

and then send (☝️ check Gist to see how i pass order information.):

$user->notify(new OrderNotification($order));
  1. Another way is using Notification facade. This approach is useful when you need to send a notification to multiple notifiable entities such as a collection of users:
use Illuminate\Support\Facades\Notification;

Notification::send($users, new OrderNotification($order));

Notification::route('slack', env('SLACK_WEBHOOK'))->notify(new SimpleNotification());

Get more out of Slack Notifications

You can find a set of blocks here for formatting beautiful Slack Notifications. You can also give action choices to the user with actionsBlock() available here.

Conclusion

We often need to get notified when something happens on the App. Get timely updates from your Laravel application with the help of Slack notifications. You can set it up in just 10 minutes!

I hope this article was useful and saved you some time figuring out this yourself. Just don't get into Bombing your Slack channels😝!

Happy Coding!

Last updated 2 weeks ago.

driesvints, andrefelipe18 liked this article

2
Like this article? Let the author know and give them a clap!

Other articles you might like

November 18th 2024

Laravel Custom Query Builders Over Scopes

Hello 👋 Alright, let's talk about Query Scopes. They're awesome, they make queries much easier to r...

Read article
November 19th 2024

Access Laravel before and after running Pest tests

How to access the Laravel ecosystem by simulating the beforeAll and afterAll methods in a Pest test....

Read article
November 11th 2024

🍣 Sushi — Your Eloquent model driver for other data sources

In Laravel projects, we usually store data in databases, create tables, and run migrations. But not...

Read article

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.