spatie/laravel-slack-alerts
Send Slack alerts from Laravel in one line. Configure a Slack Incoming Webhook via env or config, then dispatch messages through a queued job so your app won’t fail if Slack is unavailable. Great for notifying you about noteworthy events.
Installation:
composer require spatie/laravel-slack-alerts
Publish the config file:
php artisan vendor:publish --provider="Spatie\SlackAlerts\SlackAlertsServiceProvider"
Configuration:
.env:
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXX/YYY/ZZZ
config/slack-alerts.php.First Use Case: Send a basic alert in a controller or command:
use Spatie\SlackAlerts\Facades\SlackAlert;
SlackAlert::message("User {$user->name} signed up!");
Spatie\SlackAlerts\Facades\SlackAlert (primary entry point).config/slack-alerts.php (customize channels, formatting, retries).app/Jobs/SendSlackAlert (extend or inspect for custom logic).Basic Alerts:
// Simple message
SlackAlert::message("Deployment started at " . now()->format('H:i'));
// With context (e.g., user ID, action)
SlackAlert::message("Failed login attempt for user {$user->email}", [
'user_id' => $user->id,
'ip' => request()->ip(),
]);
Channel-Specific Alerts:
// Send to a specific channel
SlackAlert::channel('alerts')->message("High CPU usage detected!");
// Default channel (configured in config)
SlackAlert::message("Weekly report generated.");
Async with Queues: The package uses Laravel queues by default. Ensure your queue worker is running:
php artisan queue:work
Customizing Messages:
Use the format() method to override default formatting:
SlackAlert::format(function ($message, $context) {
return "🚨 *Alert*: {$message}\n*Context*: " . json_encode($context);
})->message("Database backup failed");
Event-Based Alerts: Listen to Laravel events and trigger alerts:
use Illuminate\Auth\Events\Registered;
Registered::listen(function ($event) {
SlackAlert::message("New user registered: {$event->user->email}");
});
Batch Processing: Send multiple alerts in a loop (e.g., for bulk actions):
foreach ($failedJobs as $job) {
SlackAlert::message("Job {$job->id} failed: {$job->exception}");
}
Log::error("Payment failed for user {$user->id}", ['user' => $user]);
SlackAlert::message("Payment failed for {$user->email}");
local vs. production:
$channel = config('slack-alerts.channels.default') === 'general'
? 'dev-alerts'
: 'production-alerts';
SlackAlert::channel($channel)->message("Environment: " . app()->environment());
throttle middleware or a decorator).Webhook Validation:
Queue Failures:
config/slack-alerts.php). Monitor failed jobs:
php artisan queue:failed
use Spatie\SlackAlerts\Jobs\SendSlackAlert;
class CustomSendSlackAlert extends SendSlackAlert {
public function failed(Throwable $exception) {
Log::error("Slack alert failed: " . $exception->getMessage());
// Send fallback notification (e.g., email)
}
}
Message Formatting:
SlackAlert::format() to sanitize or truncate messages:
SlackAlert::format(fn ($msg) => Str::limit($msg, 200))->message($longMessage);
Channel Mismatches:
SlackAlert::channel() matches exactly (including case) with Slack’s channel name or ID.curl -X GET -H "Authorization: Bearer YOUR_TOKEN" "https://slack.com/api/conversations.list"
Rate Limits:
Check Job Execution:
'max_retries' => 0, // in config/slack-alerts.php
queue:listen for real-time feedback:
php artisan queue:listen
Log Webhook Responses:
use Spatie\SlackAlerts\Jobs\SendSlackAlert;
class DebugSendSlackAlert extends SendSlackAlert {
protected function sendToSlack($message) {
$response = Http::post(config('slack-alerts.webhook_url'), ['text' => $message]);
Log::debug('Slack response:', ['status' => $response->status(), 'body' => $response->body()]);
return $response->successful();
}
}
Test Locally:
ngrok http 8000
.env to point to your ngrok URL:
SLACK_WEBHOOK_URL=https://your-ngrok-url.ngrok.io/slack-webhook
Custom Job: Override the default job to add logic (e.g., logging, fallback notifications):
// config/slack-alerts.php
'job' => \App\Jobs\CustomSlackAlertJob::class;
Dynamic Webhook URLs: Use a closure to fetch the webhook URL dynamically (e.g., from a service or cache):
SlackAlert::setWebhookUrl(fn () => Cache::get('slack_webhook_url'));
Attachments/Blocks: Leverage Slack’s message attachments or blocks:
SlackAlert::message("Deployment failed!", [
'attachments' => [
[
'title' => 'Error Details',
'text' => 'See logs at: ' . route('logs'),
'color' => '#ff0000',
],
],
]);
Environment-Specific Config:
Use Laravel’s config() helper to switch behavior:
$webhook = config('slack-alerts.webhook_url.' . app()->environment());
SlackAlert::setWebhookUrl($webhook);
Mocking for Tests: Use Laravel’s HTTP mocking to test alerts without hitting Slack:
Http::fake([
config('slack-alerts.webhook_url') => Http::response(['ok' => true], 200),
]);
SlackAlert::message("Test alert");
How can I help you explore Laravel packages today?