Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Slack Alerts Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-slack-alerts
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\SlackAlerts\SlackAlertsServiceProvider"
    
  2. Configuration:

    • Set your Slack webhook URL in .env:
      SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXX/YYY/ZZZ
      
    • Optionally configure channels, default message format, or retry logic in config/slack-alerts.php.
  3. First Use Case: Send a basic alert in a controller or command:

    use Spatie\SlackAlerts\Facades\SlackAlert;
    
    SlackAlert::message("User {$user->name} signed up!");
    

Where to Look First

  • Facade: Spatie\SlackAlerts\Facades\SlackAlert (primary entry point).
  • Config: config/slack-alerts.php (customize channels, formatting, retries).
  • Jobs: app/Jobs/SendSlackAlert (extend or inspect for custom logic).

Implementation Patterns

Core Workflows

  1. 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(),
    ]);
    
  2. 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.");
    
  3. Async with Queues: The package uses Laravel queues by default. Ensure your queue worker is running:

    php artisan queue:work
    
  4. 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");
    
  5. 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}");
    });
    
  6. 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}");
    }
    

Integration Tips

  • Logging: Combine with Laravel’s logging to correlate alerts with logs:
    Log::error("Payment failed for user {$user->id}", ['user' => $user]);
    SlackAlert::message("Payment failed for {$user->email}");
    
  • Environment Awareness: Use different channels for local vs. production:
    $channel = config('slack-alerts.channels.default') === 'general'
        ? 'dev-alerts'
        : 'production-alerts';
    SlackAlert::channel($channel)->message("Environment: " . app()->environment());
    
  • Rate Limiting: Avoid spamming Slack by throttling alerts (e.g., using throttle middleware or a decorator).

Gotchas and Tips

Pitfalls

  1. Webhook Validation:

    • Slack webhooks must be HTTPS. HTTP webhooks will fail silently.
    • Test the webhook URL using Slack’s incoming webhook tester.
  2. Queue Failures:

    • If Slack is down, the job will retry (configurable in config/slack-alerts.php). Monitor failed jobs:
      php artisan queue:failed
      
    • To handle persistent failures, extend the job:
      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)
          }
      }
      
  3. Message Formatting:

    • Slack has message formatting limits. Long messages may truncate.
    • Use SlackAlert::format() to sanitize or truncate messages:
      SlackAlert::format(fn ($msg) => Str::limit($msg, 200))->message($longMessage);
      
  4. Channel Mismatches:

    • Ensure the channel name in SlackAlert::channel() matches exactly (including case) with Slack’s channel name or ID.
    • Use Slack’s API to fetch channel IDs if unsure:
      curl -X GET -H "Authorization: Bearer YOUR_TOKEN" "https://slack.com/api/conversations.list"
      
  5. Rate Limits:

Debugging

  1. Check Job Execution:

    • Temporarily disable queue retries to debug:
      'max_retries' => 0, // in config/slack-alerts.php
      
    • Use queue:listen for real-time feedback:
      php artisan queue:listen
      
  2. Log Webhook Responses:

    • Extend the job to log 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();
          }
      }
      
  3. Test Locally:

    • Use ngrok to expose a local Slack webhook for testing:
      ngrok http 8000
      
    • Configure .env to point to your ngrok URL:
      SLACK_WEBHOOK_URL=https://your-ngrok-url.ngrok.io/slack-webhook
      

Extension Points

  1. Custom Job: Override the default job to add logic (e.g., logging, fallback notifications):

    // config/slack-alerts.php
    'job' => \App\Jobs\CustomSlackAlertJob::class;
    
  2. 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'));
    
  3. 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',
            ],
        ],
    ]);
    
  4. Environment-Specific Config: Use Laravel’s config() helper to switch behavior:

    $webhook = config('slack-alerts.webhook_url.' . app()->environment());
    SlackAlert::setWebhookUrl($webhook);
    
  5. 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");
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport