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 Laravel Package

maknz/slack

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require maknz/slack
    

    Ensure your project meets the PHP version requirements (5.5+).

  2. Slack Setup:

    • Create an incoming webhook in your Slack workspace.
    • Copy the generated webhook URL (e.g., https://hooks.slack.com/services/...).
  3. First Message:

    use Maknz\Slack\Client;
    
    $client = new Client('YOUR_WEBHOOK_URL');
    $client->send('Hello, Slack!', 'General');
    
    • Replace YOUR_WEBHOOK_URL with your actual webhook URL.
    • The first argument is the message text; the second is the channel (e.g., #general, @user).
  4. Laravel Integration (if applicable):

    • Install the Laravel wrapper:
      composer require maknz/slack-laravel
      
    • Publish the config:
      php artisan vendor:publish --provider="Maknz\Slack\SlackServiceProvider"
      
    • Configure .env with your webhook URL:
      SLACK_WEBHOOK_URL=https://hooks.slack.com/...
      

Implementation Patterns

Core Workflows

1. Sending Messages

  • Basic Text:
    $client->send('Deployment complete!', '#deployments');
    
  • Formatted Messages (using Slack's attachment format):
    $attachment = [
        'title' => 'Error Logged',
        'text' => 'Failed to process order #12345',
        'color' => '#FF0000',
        'fields' => [
            ['title' => 'Order ID', 'value' => '12345', 'short' => true],
            ['title' => 'User', 'value' => 'john.doe', 'short' => true],
        ],
    ];
    $client->send('Order Processing Error', '#errors', null, [$attachment]);
    
  • Interactive Components (e.g., buttons):
    $attachment = [
        'title' => 'Approve Deployment?',
        'text' => 'Click below to confirm:',
        'callback_id' => 'deploy_confirm',
        'actions' => [
            ['type' => 'button', 'text' => 'Approve', 'value' => 'approve', 'style' => 'primary'],
            ['type' => 'button', 'text' => 'Cancel', 'value' => 'cancel'],
        ],
    ];
    $client->send('Deployment Request', '#deployments', null, [$attachment]);
    

2. Channel Management

  • Dynamically resolve channels (e.g., from user input or config):
    $channel = config('slack.channels.alerts'); // From Laravel config
    $client->send('System Alert', $channel);
    

3. Error Handling

  • Wrap calls in try-catch to handle HTTP failures:
    try {
        $client->send('Critical Error', '#errors');
    } catch (\Maknz\Slack\Exception\SlackException $e) {
        Log::error('Slack notification failed: ' . $e->getMessage());
    }
    

4. Batch Notifications

  • Send multiple messages in a loop (e.g., for batch jobs):
    foreach ($failedJobs as $job) {
        $client->send(
            "Job {$job->id} failed: {$job->error}",
            '#job-failures'
        );
    }
    

Integration Tips

Laravel-Specific

  • Service Container Binding: Bind the client in a service provider for dependency injection:

    $this->app->singleton('slack', function ($app) {
        return new Client(config('slack.webhook_url'));
    });
    

    Use it in controllers:

    public function __construct(\Maknz\Slack\Client $slack) {
        $this->slack = $slack;
    }
    
  • Events and Listeners: Trigger Slack notifications from Laravel events:

    // In an event listener
    $this->slack->send('User registered: ' . $user->email, '#new-users');
    

Symfony-Specific

  • Use the NexySlackBundle for dependency injection and configuration:
    # config.yml
    nexy_slack:
        webhook_url: '%slack_webhook_url%'
    
    Inject the client in services:
    use Nexy\SlackBundle\Client\SlackClientInterface;
    
    public function __construct(SlackClientInterface $slack) { ... }
    

Custom Helpers

  • Create a facade or helper class to standardize message formats:
    class SlackNotifier {
        protected $client;
    
        public function __construct(Client $client) {
            $this->client = $client;
        }
    
        public function alert($message, $channel, array $context = []) {
            $attachment = [
                'title' => 'Alert',
                'text' => $message,
                'fields' => $this->formatContext($context),
            ];
            $this->client->send('ALERT', $channel, null, [$attachment]);
        }
    
        protected function formatContext(array $context) {
            // Custom logic to format context data
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning:

  2. Attachment Format Changes:

    • Slack’s API has evolved since 2015. Some attachment fields (e.g., mrkdwn for markdown) may not work as expected. Test thoroughly.
  3. Rate Limiting:

    • Slack’s incoming webhooks have rate limits (1000 messages/second). Avoid spamming in loops.
  4. Webhook URL Exposure:

    • Hardcoding webhook URLs in code is a security risk. Always use environment variables (e.g., .env in Laravel).
  5. Error Handling:

    • The package throws Maknz\Slack\Exception\SlackException for HTTP errors (e.g., invalid webhook). Catch and log these gracefully.

Debugging

  • Enable Debugging: The package uses Guzzle under the hood. Enable Guzzle’s debug mode to inspect requests:

    $client = new Client($webhookUrl);
    $client->getHttpClient()->setDebug(true); // Requires Guzzle 6+
    

    Log the debug output to inspect payloads:

    $client->send('Test', '#test');
    // Check Guzzle's debug output for the raw request payload
    
  • Validate Payloads: Use Slack’s webhook tester to verify your messages render correctly.

Configuration Quirks

  • Laravel Config: The Laravel wrapper expects a slack config key:

    // config/slack.php
    return [
        'webhook_url' => env('SLACK_WEBHOOK_URL'),
        'channels' => [
            'alerts' => '#alerts',
            'deployments' => '#deployments',
        ],
    ];
    
  • Default Channel: If no channel is provided, the package defaults to #general. Override this in the constructor:

    $client = new Client($webhookUrl, ['default_channel' => '#custom-channel']);
    

Extension Points

  1. Custom HTTP Client: Replace the default HTTP client (Guzzle) by extending the Client class:

    use Maknz\Slack\Client as BaseClient;
    use GuzzleHttp\Client as GuzzleClient;
    
    class CustomSlackClient extends BaseClient {
        public function __construct($webhookUrl, array $options = []) {
            $this->setHttpClient(new GuzzleClient($options));
            parent::__construct($webhookUrl, $options);
        }
    }
    
  2. Message Formatting: Create a decorator to transform messages before sending:

    class SlackMessageDecorator {
        protected $client;
    
        public function __construct(Client $client) {
            $this->client = $client;
        }
    
        public function send($message, $channel, array $attachments = []) {
            $formattedMessage =
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware