Laravel Slack Notification Channel
repository·3.x·Indexed 21 days ago
https://github.com/laravel/slack-notification-channelOfficial integration for sending notifications from Laravel applications to Slack via webhooks. It provides the SlackWebhookChannel for routing notifications, SlackMessage and SlackAttachment for legacy messaging, and a comprehensive set of Block Kit components including ActionsBlock, ContextBlock, ImageBlock, and SectionBlock for creating rich, interactive Slack messages.
What's inside laravel-slack-notification-channel
- The official documentation for using the Slack Notification Channel within Laravel, including setup and usage guides, is hosted on the Laravel website.
Upgrade to Slack Notifications Channel 3.0
3.xVersion 3.0 introduces a new way to write Slack notifications using the Slack BlockKit API. While previous notification formats remain supported for backward compatibility, upgrading to 3.0 allows you to leverage the more advanced BlockKit API for richer message layouts. To transition to the new format, you should rewrite your existing notifications following the patterns defined in the official Laravel documentation.Route Slack notifications to a webhook URL
3.xFor the
SlackWebhookChannelto function, the object receiving the notification must define where the webhook should be sent. Implement therouteNotificationForSlackmethod (orrouteNotificationForwith the'slack'argument) on your notifiable model to return the webhook URL.public function routeNotificationForSlack($notification) { return 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'; }Configure a SlackMessage
3.xThe
SlackMessageclass is used to construct the payload for Slack notifications. You can configure the destination channel, fallback text, username, and visual identity (icon/image). It also supports threading viathreadTimestampand controlling link/media unfurling.use Illuminate\Notifications\Slack\SlackMessage; SlackMessage::to('general') ->text('This is the fallback text') ->username('My Bot') ->emoji(':robot_face:') ->unfurlLinks() ->unfurlMedia();Create an ActionsBlock for Slack Block Kit
3.xThe
ActionsBlockclass is used to define an interactive section in a Slack message using Block Kit. It acts as a container for interactive elements like buttons and select menus.Key constraints:
- You must add at least one element to the block.
- There is a maximum of 25 elements allowed per
ActionsBlock. - The
block_id(set via theid()method) must not exceed 255 characters.
Use the
id()method to provide a unique identifier. This is useful when handling interaction payloads from Slack to identify which block triggered an action.use Illuminate\Notifications\Slack\BlockKit\Blocks\ActionsBlock; $block = (new ActionsBlock()) ->id('my_unique_block_id') ->button('Click Me') ->staticSelect('Choose an option');Build a legacy Slack message with SlackMessage
3.xThe
SlackMessageclass is used to construct messages using Slack's legacy attachment-based messaging format. It provides a fluent interface to set the message content, destination channel, sender identity, and visual styling based on the notification level.Available Levels and Colors
The visual color of the message attachment is automatically determined by the level set via these methods:
success(): Sets level tosuccess(color:good)error(): Sets level toerror(color:danger)warning(): Sets level towarning(color:warning)info(): Sets level toinfo(no specific color mapping)
use Illuminate\Notifications\Messages\SlackMessage; SlackMessage::create()\n ->content('Hello World!')\n ->success()\n ->to('#general');Create an ImageBlock for Slack Block Kit
3.xUse the
ImageBlockclass to include images in your Slack notifications via Block Kit. AnImageBlockrequires a URL for the image and an alternative text description (altText).Properties and Constraints
- URL: The image URL (max 3000 characters).
- Alt Text: A plain-text summary of the image (max 2000 characters). Note: This is required when converting the block to an array.
- Block ID: An optional unique identifier used to identify the source of an action when receiving interaction payloads (max 255 characters).
- Title: An optional
PlainTextOnlyTextObjectthat serves as a title for the image.
Methods
__construct(string $url, ?string $altText = null): Initializes the block.id(string $id): Sets a uniqueblock_id.alt(string $altText): Sets or updates the alternative text.title(string $title): Sets an optional title using aPlainTextOnlyTextObject.
use Illuminate\Notifications\Slack\BlockKit\Blocks\ImageBlock; $imageBlock = ImageBlock::id('user-profile-image') ->title('Profile Picture') ->alt('A photo of the user') ->url('https://example.com/image.png');Send Slack notifications via SlackWebhookChannel
3.xThe
SlackWebhookChannelis used to send notifications to Slack using incoming webhooks.To use this channel, your
notifiableentity (e.g., a User or Team model) must implement arouteNotificationFormethod that returns the Slack webhook URL when requested for the'slack'channel.When a notification is sent, the channel calls the
toSlackmethod on your notification class. This method should return either aIlluminate\Notifications\Slack\SlackMessageor a legacyIlluminate\Notifications\Messages\SlackMessageobject.public function toSlack($notifiable) { return (new SlackMessage) ->content('Hello, Slack!'); }Configure the visual style of a ConfirmObject
3.xYou can control the color scheme of the confirmation button using the
styleproperty.- Use the
danger()method to set the style todanger. This displays the button with a red background on desktop or red text on mobile. - If no style is specified, it defaults to
primary, which displays a green background on desktop or blue text on mobile.
$confirmObject = (new ConfirmObject())->danger();- Use the
Configure attachment fields using SlackAttachment::field()
3.xThe
field()method allows you to add structured data to an attachment. It supports two ways of defining fields:Simple Key-Value Pair: Pass a string title and a string content. The title acts as the key.
$attachment->field('Key', 'Value');Closure for Complex Fields: Pass a
Closureas the first argument. The closure receives aSlackAttachmentFieldinstance, allowing for more granular control (e.g., setting markdown content).$attachment->field(function (SlackAttachmentField $field) { $field->title('Key')->content('Value'); });
// Simple key-value $attachment->field('Status', 'Completed'); // Using a closure for advanced configuration $attachment->field(function ($field) { $field->title('Details'); $field->content('This is a complex field'); });Add a confirmation dialog to a ButtonElement
3.xYou can attach an optional confirmation dialog to a button using the
confirmmethod. This prevents accidental clicks by prompting the user before the action is executed.When calling
confirm, you must provide the confirmation text. You can optionally provide a callback to configure theConfirmObject.$button = new ButtonElement('Delete Record'); $button->confirm('Are you sure you want to delete this?', function ($confirm) { // Configure the confirm object if needed });Configure Slack message link unfurling and name linking
3.xUse these methods to control how Slack handles links and mentions within your message:
linkNames(): Enables automatic linking of channel names and usernames.unfurlLinks($unfurlLinks): A boolean flag to determine if Slack should provide a preview of links in the message.unfurlMedia($unfurlMedia): A boolean flag to determine if Slack should provide a preview of media links.
SlackMessage::create() ->content('Check out #general and https://example.com') ->linkNames() ->unfurlLinks(true) ->unfurlMedia(true);