If you're looking to send Slack notifications to your company's Slack channel when system events happen such as new user created, payment received, etc, then this guide is for you. We'll be using Laravel's built-in logging channels to "log" messages to our Slack channel. The idea is so simple, it took me many years to finally realize how easy it can be.
You'll need to create a webhook URL using a Slack app. You can follow Slack's Sending your first Slack message guide.
Once you've setup your new Slack app, create a new webhook URL and copy it your clipboard.
We'll need to take the webhook URL that's copied to your clipboard and add it as a new environment variable. I like to call the environment variable
LOGSLACKWEBHOOK_URL, but you can name it whatever you like:
The last configuration step is creating the new log channel. Open up the
logging.php file. We'll want to copy the exiting
slack channel and create a new one:
1<?php23return [4 'slack' => [5 'driver' => 'slack',6 'url' => env('LOG_SLACK_WEBHOOK_URL'),7 'username' => 'Oh See Snaps',8 'emoji' => ':boom:',9 'level' => 'error'10 ],1112 'slackNotification' => [13 'driver' => 'slack',14 'url' => env('LOG_SLACK_WEBHOOK_URL'),15 'username' => 'Oh See Snaps',16 'emoji' => ':wave:',17 'level' => 'info'18 ]19];
Note that we changed the
level from "error" to "info". That will allow any log message with an INFO level or above to be sent to the Slack channel.
That's all we have to do for configuration! Now we can start sending system notifications to our Slack channel. Here's an example where I am sending a notification whenever a new user is created:
1<?php23Log::channel('slackNotification')->info('New user created', [4 'name' => $user->name,5 'email' => $user->email6]);
In Slack, the message comes through like this:
This guide is for sending simple notifications to your Slack channel. If you need more control or customization options, be sure to check out Laravel's documentation on Slack Notification channels: https://laravel.com/docs/8.x/notifications#slack-notifications
Hopefully you found this article useful! If you did, share it on Twitter!
Found an issue with the article? Submit your edits against the repository.