Discover how to integrate Slack and Laravel to send important notifications to your team for improved communication and productivity. Learn how this powerful tool can benefit your sales team and beyond.
Table of contents
Problem statement
You have a requirement of sending notification to a specific slack channel using Laravel. You need to configure the incoming Slack WebHook on your Slack channel and then send notification from Laravel application.
Solution
Slack offers many ways for integration with external services. I’ll be using WebHooks to satisfy the requirement. This requires admin access to slack workspace.
Configure Slack Incoming WebHook
- Navigate to the Slack channel you want to send notifications to.
- Click channel details.
- Click Integrations.
- Click Add apps in apps card.
- Search WebHook.
- Click Install on Incoming WebHooks.
- Select add to slack.
- From dropdown select the channel.
- Click add Incoming WebHook Integration.
After that, On the Incoming WebHooks page, from the WebHook URL field, copy the WebHook URL, you should have a link something like:
https://hooks.slack.com/services/your_unique_identifiers
Installing and configuring packages
Laravel offers official slack channel package. We can install it by composer.
composer require laravel/slack-notification-channel
Create a Laravel Notification.
php artisan make:notification SendSlackNotification
And then update the Notification as follows:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;
class SendSlackNotification extends Notification {
use Queueable;
public $level;
public $message;
/**
* Create a new notification instance.
*
* @return void
* */
public function __construct(string $level, string $message)
{
$this->level = $level;
$this->message = $message;
}
/**
* Get the notification's delivery channels.
*
* @return array
* */
public function via() {
return ['slack'];
}
/**
* Get the Slack representation of the notification.
* * * @return \Illuminate\Notifications\Messages\SlackMessage
* */
public function toSlack() {
$slackMessage = new SlackMessage();
$slackMessage->level = $this->level;
$slackMessage->content = $this->message;
return $slackMessage;
}
}
Sending notification
Sending notifications on-demand. Laravel provides an on-demand notification facade.
<?php
use Illuminate\Support\Facades\Notification;
$slackWebhookUrl = 'https://hooks.slack.com/services/your_unique_ids';
$message = 'Test message';
Notification::route('slack', $slackWebhookUrl)
->notify(new SendSlackNotification('success', $message));
Conclusion
Congratulations 🎉, you can use the Notification route to trigger dynamic notifications from anywhere in the application. There are a lot of improvements can be made added. My goal was to get you started quickly.