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 notifications to Slack. Integrates with Laravel’s Notifications system, letting you route messages to Slack channels or users and customize payloads. See Laravel docs for configuration and usage.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require laravel/slack-notification-channel
    

    Publish the config (if needed):

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

    SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXX/YYY/ZZZ
    
  3. First Notification: Create a notification class (e.g., app/Notifications/SlackAlert.php):

    use Illuminate\Notifications\Notification;
    use Laravel\SlackNotificationChannel\SlackMessage;
    
    class SlackAlert extends Notification
    {
        public function via($notifiable)
        {
            return ['slack'];
        }
    
        public function toSlack($notifiable)
        {
            return (new SlackMessage)
                ->content('Hello from Laravel!')
                ->attachment(function ($attachment) {
                    $attachment->title('New Alert')
                               ->text('Check this out!');
                });
        }
    }
    
  4. Send the Notification:

    use App\Notifications\SlackAlert;
    use App\Models\User; // or any notifiable model
    
    $user = User::find(1);
    $user->notify(new SlackAlert());
    

Where to Look First

  • Official Docs: Laravel Slack Notifications
  • Package Source: Focus on SlackMessage and SlackWebhookChannel classes in src/.
  • Config: config/services.php for Slack credentials and defaults.

Implementation Patterns

Core Workflows

1. Basic Alerts

Use SlackMessage for simple text-based notifications:

return (new SlackMessage)
    ->content('Deployment failed on staging!')
    ->from('Laravel CI', ':robot_face:');

2. Rich Attachments

Leverage Slack’s attachment fields for structured data:

return (new SlackMessage)
    ->attachment(function ($attachment) {
        $attachment->title('Order #12345')
                   ->fields([
                       ['title' => 'Customer', 'value' => 'John Doe', 'short' => true],
                       ['title' => 'Amount', 'value' => '$99.99', 'short' => true],
                   ])
                   ->footer('Paid at ' . now()->format('H:i'));
    });

3. BlockKit Messages (v3.6+)

Use Slack’s BlockKit for interactive elements (buttons, modals, selects):

return (new SlackMessage)
    ->blockKit([
        'type' => 'section',
        'text' => [
            'type' => 'mrkdwn',
            'text' => 'Approve this payment?',
        ],
        'accessory' => [
            'type' => 'button',
            'text' => [
                'type' => 'plain_text',
                'text' => 'Approve',
            ],
            'action_id' => 'approve_payment',
        ],
    ]);
  • Pro Tip: Use the Block Kit Builder to generate JSON, then paste it into your blockKit() method.

4. Threaded Replies (v3.3+)

Reply to existing Slack messages in threads:

return (new SlackMessage)
    ->content('Follow-up: Issue resolved!')
    ->threadTimestamp('1620000000.000123'); // Original message's timestamp

5. Conditional Notifications (v3.0.1+)

Skip notifications based on logic:

public function via($notifiable)
{
    return $notifiable->shouldReceiveAlerts ? ['slack'] : [];
}

6. Dynamic Webhook URL

Override the webhook URL per notification:

public function toSlack($notifiable)
{
    return (new SlackMessage)
        ->webhookUrl($notifiable->slack_webhook_url)
        ->content('Custom webhook used!');
}

7. Interactive Components (v3.7+)

Add user selects or buttons with callbacks:

return (new SlackMessage)
    ->blockKit([
        'type' => 'section',
        'text' => [
            'type' => 'mrkdwn',
            'text' => 'Select an option:',
        ],
        'accessory' => [
            'type' => 'users_select',
            'placeholder' => 'Choose a user...',
            'action_id' => 'select_user',
        ],
    ]);

Integration Tips

1. Queue Notifications

Use Laravel’s queue system to avoid blocking requests:

$user->notify(new SlackAlert())->onQueue('slack');

2. Rate Limiting

Configure Slack’s rate limits (1 per second by default). Use sleep() or queues to throttle:

if ($lastSentAt && now()->diffInSeconds($lastSentAt) < 1) {
    sleep(1);
}

3. Error Handling

Wrap Slack calls in try-catch blocks to log failures:

try {
    $user->notify(new SlackAlert());
} catch (\Exception $e) {
    \Log::error('Slack notification failed', ['error' => $e->getMessage()]);
}

4. Testing

Use Laravel’s NotificationFake for unit tests:

use Illuminate\Support\Facades\Notification;

Notification::fake();
$user->notify(new SlackAlert());
Notification::assertSentTo($user, SlackAlert::class);

5. Environment-Specific Config

Use .env variables to switch between dev/staging/prod webhooks:

SLACK_WEBHOOK_URL=${SLACK_WEBHOOK_URL:-http://localhost/slack-webhook}

6. Customizing the Channel

Extend SlackWebhookChannel for reusable logic:

namespace App\Notifications\Channels;

use Laravel\SlackNotificationChannel\SlackWebhookChannel;

class CustomSlackChannel extends SlackWebhookChannel
{
    public function send($notifiable, Notification $notification)
    {
        // Custom logic before sending
        $result = parent::send($notifiable, $notification);

        // Custom logic after sending
        return $result;
    }
}

Then register it in AppServiceProvider:

Notification::extend('custom_slack', function ($app) {
    return new CustomSlackChannel();
});

Gotchas and Tips

Pitfalls

  1. Webhook URL Validation:

    • Slack webhooks must use https. HTTP URLs will fail silently.
    • Fix: Validate the URL in config or notification class:
      if (!str_starts_with(config('services.slack.webhook_url'), 'https')) {
          throw new \InvalidArgumentException('Slack webhook must use HTTPS.');
      }
      
  2. Attachment Size Limits:

    • Slack limits attachments to 1MB for text and 5MB for files.
    • Fix: Use ->text() for large content or link to external resources.
  3. Thread Timestamps:

    • Incorrect threadTimestamp values will create new threads instead of replies.
    • Fix: Ensure timestamps match Slack’s format (e.g., 1620000000.000123).
  4. BlockKit Validation:

  5. Rate Limits:

    • Slack enforces 1 message per second per webhook.
    • Fix: Implement exponential backoff or use queues.
  6. Empty Routes:

    • Notifications with empty via() or invalid channels may fail silently.
    • Fix: Add validation:
      public function via($notifiable)
      {
          return $notifiable->slack_channel ? ['slack'] : [];
      }
      
  7. Deprecated Methods:

    • Older versions used ->toSlack() directly. Prefer SlackMessage for consistency.
    • Fix: Update to use SlackMessage builder methods.

Debugging Tips

  1. Log Raw Payloads: Override buildJsonPayload() to log the final payload:
    public function buildJsonPayload($notifiable, $notification)
    {
        $payload
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai