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

Slack Notification Channel Laravel Package

laravel/slack-notification-channel

Official Laravel notification channel for sending rich Slack messages via webhooks. Integrates with Laravel’s Notifications system, supports attachments/blocks, and works seamlessly with queues and notifiables for app alerts and updates.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/slack-notification-channel
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Laravel\SlackNotificationChannel\SlackServiceProvider"
    
  2. Configure Slack: Add your Slack webhook URL to .env:

    SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
    
  3. First Notification: Create a notification class extending SlackMessage:

    use Laravel\SlackNotificationChannel\SlackMessage;
    
    class DeploymentFailedNotification extends SlackMessage
    {
        public function __construct(public string $message)
        {
            $this->message = $message;
        }
    }
    
  4. Send the Notification:

    use App\Notifications\DeploymentFailedNotification;
    use Illuminate\Support\Facades\Notification;
    
    Notification::route('slack', '#general')
                ->notify(new DeploymentFailedNotification('Deployment failed!'));
    

Key Starting Points

  • Official Docs: Laravel Slack Notifications
  • Config File: config/services.php (for slack key)
  • Channel Class: SlackWebhookChannel (handles delivery)

Implementation Patterns

Core Workflows

  1. Basic Text Messages:

    Notification::route('slack', '#alerts')->notify(new SlackMessage('Hello, Slack!'));
    
  2. Rich Attachments (Legacy):

    class AlertNotification extends SlackMessage
    {
        public function toSlack($notifiable)
        {
            return [
                'text' => 'Critical Alert!',
                'attachments' => [
                    [
                        'title' => 'Error Details',
                        'text' => 'Check logs at: ' . url('/logs'),
                        'color' => '#ff0000',
                    ],
                ],
            ];
        }
    }
    
  3. BlockKit (Modern UI):

    class InteractiveNotification extends SlackMessage
    {
        public function toSlack($notifiable)
        {
            return [
                'blocks' => [
                    [
                        'type' => 'section',
                        'text' => [
                            'type' => 'mrkdwn',
                            'text' => 'Deploy *now*?',
                        ],
                    ],
                    [
                        'type' => 'actions',
                        'elements' => [
                            [
                                'type' => 'button',
                                'text' => 'Deploy',
                                'value' => 'deploy',
                                'action_id' => 'deploy_action',
                            ],
                        ],
                    ],
                ],
            ];
        }
    }
    
  4. Threaded Replies:

    Notification::route('slack', '#general')
                ->notify(new SlackMessage('Initial message'))
                ->replyTo('thread_ts'); // Attach to existing thread
    
  5. Conditional Logic:

    class DynamicNotification extends SlackMessage
    {
        public function __construct(public bool $isCritical)
        {
        }
    
        public function toSlack($notifiable)
        {
            return $this->isCritical
                ? ['text' => 'CRITICAL: System down!', 'blocks' => [...]]
                : ['text' => 'Info: Maintenance scheduled'];
        }
    }
    

Integration Tips

  • Queue Notifications:
    Notification::route('slack', '#logs')->notify(new SlackMessage('...'))->delay(now()->addMinutes(5));
    
  • Route to Users:
    Notification::route('slack', 'U12345678')->notify(new SlackMessage('DM for you!'));
    
  • Use with Events:
    event(new DeploymentEvent($repo));
    // In listener:
    Notification::route('slack', '#dev')->notify(new DeploymentNotification($event));
    
  • BlockKit Builder: Copy JSON from Slack Block Kit Builder and use:
    public function toSlack($notifiable)
    {
        return ['blocks' => json_decode(file_get_contents('path/to/blocks.json'), true)];
    }
    

Gotchas and Tips

Common Pitfalls

  1. Empty Routes:

    • Issue: Notifications fail silently if route() is empty.
    • Fix: Validate routes before sending:
      if (empty($route)) throw new \Exception('Slack route not configured');
      
  2. BlockKit Validation:

    • Issue: Slack rejects malformed BlockKit JSON.
    • Fix: Use the Block Kit Builder to validate payloads before implementation.
  3. Rate Limits:

    • Issue: Slack throttles requests (~1 per second for webhooks).
    • Fix: Queue notifications or implement exponential backoff:
      $this->queueOn('slack_queue');
      
  4. Attachment Limits:

    • Issue: Slack limits attachments to 100 per message.
    • Fix: Split large payloads into multiple notifications or use files.
  5. Threading:

    • Issue: thread_ts must match an existing message timestamp.
    • Fix: Store timestamps in your database or use replyTo() with the original notification’s id.

Debugging Tips

  • Check Payloads: Override buildJsonPayload() to log raw output:
    protected function buildJsonPayload($notifiable, $message)
    {
        \Log::debug('Slack Payload:', ['payload' => $message]);
        return parent::buildJsonPayload($message);
    }
    
  • Test Locally: Use ngrok to expose a local Slack webhook for testing:
    ngrok http 8000
    
    Configure .env:
    SLACK_WEBHOOK_URL=https://your-ngrok-url.ngrok.io/slack
    

Configuration Quirks

  • Dynamic Disabling: Disable the channel dynamically:
    $channel = app('notifications')->createSlackChannel();
    $channel->disableRouteValidation(); // Skip route checks
    
  • Custom HTTP Client: Bind a custom Guzzle client in AppServiceProvider:
    $this->app->bind(\GuzzleHttp\Client::class, function () {
        return new \GuzzleHttp\Client(['timeout' => 10]);
    });
    

Extension Points

  1. Custom Slack Client: Extend SlackWebhookChannel to add retries or logging:

    class CustomSlackChannel extends \Laravel\SlackNotificationChannel\SlackWebhookChannel
    {
        public function send($notifiable, $message)
        {
            \Log::info('Sending Slack message', ['to' => $this->route]);
            return parent::send($notifiable, $message);
        }
    }
    

    Register in config/notifications.php:

    'channels' => [
        'slack' => [
            'driver' => 'slack-custom',
        ],
    ],
    
  2. Add Metadata: Attach custom fields to payloads:

    class MetadataNotification extends SlackMessage
    {
        public function toSlack($notifiable)
        {
            return [
                'text' => 'Notification with metadata',
                'metadata' => ['user_id' => $notifiable->id, 'source' => 'api'],
            ];
        }
    }
    
  3. Interactive Components: Handle Slack actions via a route:

    Route::post('/slack/actions', function (Request $request) {
        $payload = $request->json()->all();
        if ($payload['actions'][0]['name'] === 'deploy_action') {
            // Handle deployment
        }
    });
    

Pro Tips

  • Use via() for Multi-Channel:
    class MultiChannelNotification implements ShouldQueue
    {
        public function via($notifiable)
        {
            return ['mail', 'slack'];
        }
    }
    
  • Environment-Specific Routes:
    $route = config('services.slack.route') ?? '#general';
    Notification::route('slack', $route)->notify(...);
    
  • Monitor Deliveries: Extend the channel to track failures:
    class TrackedSlackChannel extends SlackWebhookChannel
    {
        public function send($notifiable, $message)
        {
            try {
                return parent::send($notifiable, $message);
            } catch (\Exception $e) {
                \DB::table('failed_jobs')->insert([...]);
                throw $e;
            }
        }
    }
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony