Installation:
composer require displayce/slack-bundle
Add to config/bundles.php:
return [
// ...
Displayce\SlackBundle\SlackBundle::class => ['all' => true],
];
Configuration: Publish the default config:
php bin/console config:dump-reference DisplayceSlackBundle
Update config/packages/displayce_slack.yaml:
displayce_slack:
token: '%env(SLACK_API_TOKEN)%' # Your Slack API token
default_channel: '#general' # Optional default channel
First Use Case: Inject the API client in a controller/service:
use Displayce\SlackBundle\Client\ApiClientInterface;
public function __construct(private ApiClientInterface $slackClient) {}
public function sendNotification()
{
$payload = new \Displayce\SlackBundle\Payload\ChatPostMessagePayload();
$payload->setChannel('#general')
->setText('Hello from Laravel!')
->setUsername('LaravelBot');
$response = $this->slackClient->send($payload);
return $response->getTs(); // Timestamp of the message
}
$payload = new ChatPostMessagePayload();
$payload->setChannel('#channel')
->setText('Hello, world!');
$this->slackClient->send($payload);
$payload->setText('*Bold text* and _italic text_ with `code`');
$attachment = new Attachment();
$attachment->setText('Attachment content')
->setColor('#36a64f');
$payload->addAttachment($attachment);
sendAsync() for non-blocking calls (if supported by the underlying library).
$this->slackClient->sendAsync($payload)->then(function ($response) {
// Handle response
});
try {
$response = $this->slackClient->send($payload);
} catch (\Displayce\SlackBundle\Exception\SlackException $e) {
Log::error('Slack API error: ' . $e->getMessage());
}
$channel = $this->getChannelFromUserInput($userInput);
$payload->setChannel($channel);
default_channel in config/packages/displayce_slack.yaml to avoid hardcoding.Illuminate\Auth\Events\Registered):
public function handle(Registered $event)
{
$payload = new ChatPostMessagePayload();
$payload->setText("New user registered: {$event->user->email}");
$this->slackClient->send($payload);
}
SendSlackNotification::dispatch($payload)->onQueue('slack');
.env variables:
# config/packages/displayce_slack.yaml
displayce_slack:
token: '%env(SLACK_TOKEN_PROD)%' # Override per environment
class AlertPayload extends ChatPostMessagePayload
{
public function __construct(string $message, string $color = '#ff0000')
{
$this->setText($message)
->setAttachments([new Attachment(['color' => $color])]);
}
}
Token Security:
.env:
SLACK_API_TOKEN=xoxb-your-token-here
chat:write).Channel Format:
# (e.g., #general). Omitting this will fail silently or return an error.@username format, not #.Rate Limiting:
429 Too Many Requests errors gracefully:
catch (\Displayce\SlackBundle\Exception\RateLimitException $e) {
sleep($e->getRetryAfter());
retry();
}
Deprecated Methods:
displayce/slack library is unmaintained (last release: 2020). Some methods (e.g., sendAsync) may not work as expected. Test thoroughly.Payload Validation:
channel or text) before sending:
if (empty($payload->getChannel()) && empty($payload->getUser())) {
throw new \InvalidArgumentException('Channel or user must be specified.');
}
Enable Verbose Logging:
Add to config/packages/monolog.yaml:
handlers:
slack:
type: stream
path: "%kernel.logs_dir%/slack.log"
level: debug
Then enable debug mode in config/packages/displayce_slack.yaml:
displayce_slack:
debug: true
Inspect Raw Responses: Dump the raw response object to debug API issues:
$response = $this->slackClient->send($payload);
\Log::debug('Slack Response:', ['raw' => $response->getData()]);
Test with Slack CLI:
Use slack-cli to manually test API calls before integrating:
slack chat.postMessage --token=xoxb-your-token --channel=#general --text="Test message"
Reusable Payload Builders: Create static methods for common payloads:
class SlackNotifier
{
public static function alert(string $message, string $channel = '#alerts'): ChatPostMessagePayload
{
$payload = new ChatPostMessagePayload();
$payload->setChannel($channel)
->setText($message)
->setUsername('AlertBot')
->setIconEmoji(':bell:');
return $payload;
}
}
Environment-Specific Channels: Use Laravel's config caching to switch channels per environment:
# config/packages/displayce_slack.yaml
displayce_slack:
channels:
dev: '#dev-channel'
prod: '#prod-channel'
Then dynamically set:
$payload->setChannel(config('displayce_slack.channels.' . app()->environment()));
Webhook Fallback: If the API client fails, fall back to Slack Incoming Webhooks:
$webhookUrl = config('services.slack.webhook_url');
$ch = curl_init($webhookUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'text' => 'Fallback message',
'username' => 'FallbackBot'
]));
curl_exec($ch);
Extend Payload Classes: Override payload classes to add custom logic:
class CustomPayload extends ChatPostMessagePayload
{
public function setAsAdmin(): self
{
$this->setUsername('AdminBot')
->setIconEmoji(':shield:');
return $this;
}
}
Monitor API Usage: Use Slack's API Dashboard to track usage and set up alerts for anomalies.
Fallback for Missing Bundle: If the bundle fails to load, manually instantiate the client:
use Displayce\Slack\Client;
$client = new Client(config('displayce_slack.token'));
How can I help you explore Laravel packages today?