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

Mattermost Notifier Laravel Package

symfony/mattermost-notifier

Symfony Notifier integration for Mattermost. Configure via DSN (access token, host/path, default channel) and send ChatMessage notifications, optionally overriding the recipient channel with MattermostOptions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package via Composer:

    composer require symfony/notifier
    

    (Note: The symfony/mattermost-notifier is part of the symfony/notifier bundle, so no separate package is needed.)

  2. Configure the DSN in .env:

    MATTERMOST_DSN=mattermost://ACCESS_TOKEN@HOST/PATH?channel=CHANNEL_ID
    

    Replace placeholders with your Mattermost:

    • ACCESS_TOKEN: Your Mattermost personal access token.
    • HOST: Mattermost server URL (e.g., https://mattermost.example.com).
    • PATH: Sub-path (e.g., /api/v4 for self-hosted; omit for cloud).
    • CHANNEL_ID: Default channel ID (e.g., C12345678).
  3. First notification in a Laravel controller or command:

    use Symfony\Component\Notifier\Notifier;
    use Symfony\Component\Notifier\Message\ChatMessage;
    use Symfony\Component\Notifier\Bridge\Mattermost\MattermostTransport;
    
    public function sendAlert() {
        $notifier = new Notifier(new MattermostTransport(
            env('MATTERMOST_DSN')
        ));
        $notifier->send(new ChatMessage('Hello from Laravel!'));
    }
    

First Use Case: Deployment Alerts

Trigger a notification when a Laravel job completes:

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Symfony\Component\Notifier\Notifier;
use Symfony\Component\Notifier\Message\ChatMessage;

class DeployJob implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public function handle() {
        $notifier = app(Notifier::class);
        $notifier->send(new ChatMessage('Deployment completed! 🚀'));
    }
}

Implementation Patterns

Workflow: Event-Driven Notifications

Leverage Laravel’s events to decouple notification logic:

  1. Define an event (e.g., DeploymentCompleted):

    namespace App\Events;
    
    class DeploymentCompleted
    {
        public function __construct(public string $message) {}
    }
    
  2. Listen for the event and send a notification:

    namespace App\Listeners;
    
    use App\Events\DeploymentCompleted;
    use Symfony\Component\Notifier\Notifier;
    use Symfony\Component\Notifier\Message\ChatMessage;
    
    class NotifyDeployment implements ShouldQueue
    {
        public function handle(DeploymentCompleted $event) {
            $notifier = app(Notifier::class);
            $notifier->send(new ChatMessage($event->message));
        }
    }
    
  3. Register the listener in EventServiceProvider:

    protected $listen = [
        DeploymentCompleted::class => [
            NotifyDeployment::class,
        ],
    ];
    

Workflow: Dynamic Channel Routing

Override the default channel per message:

use Symfony\Component\Notifier\Bridge\Mattermost\MattermostOptions;

$options = new MattermostOptions();
$options->recipient('C98765432'); // Target a specific channel

$message = new ChatMessage('Urgent: Server down!');
$message->options($options);

$notifier->send($message);

Integration with Laravel Notifications

Extend Laravel’s Notification class to use Symfony’s notifier:

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Symfony\Component\Notifier\Notifier;
use Symfony\Component\Notifier\Message\ChatMessage;

class MattermostAlert extends Notification
{
    use Queueable;

    public function __construct(public string $message) {}

    public function via($notifiable) {
        return ['mattermost'];
    }

    public function toMattermost($notifiable) {
        return new ChatMessage($this->message);
    }
}

Queueing Notifications

Wrap the notifier in a Laravel job for reliability:

namespace App\Jobs;

use Symfony\Component\Notifier\Notifier;
use Symfony\Component\Notifier\Message\ChatMessage;

class SendMattermostNotification implements ShouldQueue
{
    public function __construct(public string $message) {}

    public function handle() {
        $notifier = app(Notifier::class);
        $notifier->send(new ChatMessage($this->message));
    }
}

Gotchas and Tips

Pitfalls

  1. DSN Format Sensitivity:

    • Ensure the DSN follows the exact format: mattermost://TOKEN@HOST/PATH?channel=ID.
    • Debug tip: Use new MattermostTransport('mattermost://...') directly to validate the DSN before integrating with Laravel’s container.
  2. Channel ID vs. Name:

    • Mattermost requires channel IDs (e.g., C12345678), not names (e.g., #general).
    • Fix: Use the Mattermost API to fetch the ID:
      $channelId = Http::withToken(env('MATTERMOST_TOKEN'))
          ->get("https://{host}/api/v4/channels/name/{channel_name}")
          ->json()['id'];
      
  3. Authentication Failures:

    • Invalid tokens or permissions will silently fail. Enable debug logging:
      $notifier = new Notifier(new MattermostTransport(env('MATTERMOST_DSN')), [
          'debug' => true,
      ]);
      
  4. Message Length Limits:

    • Mattermost truncates messages > 4096 characters. Workaround:
      • Split long messages into multiple ChatMessage instances.
      • Use Laravel’s Str::limit() to truncate with ellipsis.
  5. Laravel Service Container Conflicts:

    • Symfony’s Notifier may conflict with Laravel’s autoloader. Solution:
      • Bind the transport explicitly in AppServiceProvider:
        $this->app->bind(MattermostTransport::class, function ($app) {
            return new MattermostTransport(env('MATTERMOST_DSN'));
        });
        

Debugging Tips

  1. Inspect Raw Requests: Use Laravel’s tap() to log the HTTP client request:

    $transport = new MattermostTransport(env('MATTERMOST_DSN'));
    $transport->getClient()->tap(function ($client) {
        $client->getOptions()['debug'] = true;
    });
    
  2. Test Locally: Use a mock transport for testing:

    use Symfony\Component\Notifier\Test\Transport\MockTransport;
    
    $mockTransport = new MockTransport();
    $notifier = new Notifier($mockTransport);
    $notifier->send(new ChatMessage('Test'));
    
    $this->assertEquals('Test', $mockTransport->getLastMessage());
    
  3. Handle Retries: Laravel’s queue system will retry failed jobs. Customize retry logic:

    class SendMattermostNotification extends Job
    {
        public function retryUntil() {
            return now()->addMinutes(5); // Retry for 5 minutes
        }
    }
    

Extension Points

  1. Custom Message Formatting: Extend ChatMessage to support Laravel Blade templates:

    use Symfony\Component\Notifier\Message\ChatMessage;
    
    class BladeChatMessage extends ChatMessage
    {
        public function __construct(string $view, array $data = []) {
            $content = view($view, $data)->render();
            parent::__construct($content);
        }
    }
    
  2. Add Attachments: Use Mattermost’s file upload API via HttpClient:

    use Symfony\Component\HttpClient\HttpClient;
    
    $client = HttpClient::create();
    $response = $client->request('POST', 'https://mattermost.example.com/api/v4/files', [
        'auth_bearer' => env('MATTERMOST_TOKEN'),
        'files' => [new \CURLFile('/path/to/file.pdf', 'application/pdf')],
    ]);
    
  3. Rate Limiting: Implement a throttle middleware for Laravel queues:

    use Illuminate\Pipeline\Pipeline;
    
    $notifier = new Notifier(new MattermostTransport(env('MATTERMOST_DSN')));
    $notifier = (new Pipeline(app()))
        ->send($notifier)
        ->through([ThrottleMattermostNotifications::class])
        ->thenReturn($notifier);
    

Configuration Quirks

  1. Environment Variables:
    • Store sensitive tokens in Laravel’s .env:
      MATTERMOST_TOKEN=your_token_here
      MATTERMOST_HOST=https://mattermost.example.com
      MATTERMOST_CHANNEL=C12345678
      
    • Dynamically build the DSN in AppServiceProvider:
      $this
      
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.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views