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

Notifier Laravel Package

symfony/notifier

Symfony Notifier sends notifications through multiple channels like email, SMS, chat, and push. It unifies message creation, routing, and transport handling, making it easy to notify users via one or several providers with a consistent API.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package:

    composer require symfony/notifier
    

    For Laravel-specific integration, use spatie/laravel-notifier (a wrapper) or manually configure Symfony’s Notifier.

  2. Configure transports (e.g., Slack, SMS, Email): Add to config/services.php or a dedicated notifier.php config file:

    'notifier' => [
        'transports' => [
            'slack' => [
                'dsn' => 'slack://token?channel=general',
            ],
            'sms' => [
                'dsn' => 'twilio://account_sid:auth_token?from=+1234567890',
            ],
        ],
    ],
    
  3. First notification (e.g., send a Slack message):

    use Symfony\Component\Notifier\Notifier;
    use Symfony\Component\Notifier\Message\SlackMessage;
    
    $notifier = new Notifier();
    $message = new SlackMessage('Hello from Laravel!');
    $notifier->send($message);
    
  4. Laravel-specific tip: Use Laravel’s service container to bind the Notifier:

    $this->app->singleton(Notifier::class, function ($app) {
        return new Notifier($app['config']['notifier.transports']);
    });
    

First Use Case: Multi-Channel Alerts

Send the same alert via email, SMS, and Slack in a single line:

use Symfony\Component\Notifier\Message\Email;
use Symfony\Component\Notifier\Message\SmsMessage;
use Symfony\Component\Notifier\Message\SlackMessage;

$notifier = app(Notifier::class);
$notifier->send([
    new Email('alert@example.com', 'Critical Alert', 'System down!'),
    new SmsMessage('+1234567890', 'System down!'),
    new SlackMessage('System down!', ['channel' => '#alerts']),
]);

Implementation Patterns

1. Transport Configuration

  • Dynamic transports: Load transports from .env or config:
    $dsn = 'slack://' . env('SLACK_TOKEN') . '?channel=' . env('SLACK_CHANNEL');
    $transport = new SlackTransport($dsn);
    $notifier->addTransport('slack', $transport);
    
  • Environment-specific routing: Use Laravel’s config() to switch transports per environment:
    $notifier->addTransport(
        'sms',
        new TwilioTransport(config('services.twilio.' . env('APP_ENV') . '.sms'))
    );
    

2. Message Customization

  • Rich messages:

    • Slack: Add buttons, sections, or blocks:
      $message = new SlackMessage('Deploy failed!');
      $message->subject('Deployment Alert');
      $message->addButton('Retry', 'https://example.com/retry');
      
    • Telegram: Use markdown formatting:
      $message = new TelegramMessage('*Critical* alert!');
      
    • Email: Attach files or use templates:
      $email = new Email('user@example.com', 'Invoice', 'body');
      $email->from(new Address('no-reply@example.com', 'Support'));
      $email->attachFromPath(storage_path('app/invoice.pdf'));
      
  • Recipient groups: Route to multiple recipients at once:

    $message = new SlackMessage('Weekly update');
    $message->recipient('team-a', 'team-b'); // Multiple channels
    

3. Asynchronous Processing

  • Laravel Queues: Dispatch notifications to a queue:
    use Symfony\Component\Notifier\NotifierInterface;
    use Illuminate\Support\Facades\Bus;
    
    Bus::dispatch(function () use ($notifier) {
        $notifier->send(new SlackMessage('Async alert!'));
    });
    
  • Symfony Messenger: For advanced workflows (e.g., retries, middleware):
    $notifier->send(new SlackMessage('Async alert!'), [
        'transport' => 'sync', // or 'async'
    ]);
    

4. Event-Driven Notifications

  • Listen for model events (e.g., created, updated):
    use Illuminate\Database\Eloquent\Model;
    
    class User extends Model {
        protected static function booted() {
            static::created(function ($user) {
                app(NotifierInterface::class)->send(
                    new SlackMessage("New user: {$user->name}")
                );
            });
        }
    }
    
  • Laravel Events: Trigger notifications from custom events:
    event(new OrderShipped($order));
    // In EventServiceProvider:
    OrderShipped::listen(function ($event) {
        $notifier->send(new Email($event->user, 'Order Shipped', 'body'));
    });
    

5. Custom Transports

Extend for proprietary APIs:

use Symfony\Component\Notifier\Transport\TransportInterface;

class CustomTransport implements TransportInterface {
    public function __send(MessageInterface $message, array $failedRecipients = []): void {
        // Implement custom logic (e.g., HTTP request to your API)
    }
    public function __supports(MessageInterface $message): bool {
        return $message instanceof CustomMessage;
    }
}

Register it:

$notifier->addTransport('custom', new CustomTransport());

Gotchas and Tips

1. Common Pitfalls

  • DSN Format: Ensure correct DSN syntax (e.g., slack://token?channel=#general).
    • Fix: Validate DSNs with Dsn::parse():
      use Symfony\Component\Notifier\Dsn;
      $dsn = Dsn::parse('slack://token');
      
  • Recipient Validation: Some transports (e.g., Twilio) require validated phone numbers.
    • Fix: Use SmsMessage::setRecipient() with E.164 format.
  • Async Deadlocks: Laravel queues may block if notifications aren’t properly dispatched.
    • Fix: Use Bus::dispatch() or dispatchSync() for critical notifications.

2. Debugging

  • Failed Notifications: Check failed_jobs table (Laravel) or Symfony’s Notifier logs.
    $notifier->send($message, ['transport' => 'slack', 'logger' => true]);
    
  • Transport-Specific Errors: Enable verbose logging:
    $transport->setLogger(new \Monolog\Logger('notifier'));
    

3. Configuration Quirks

  • Laravel Cache: Clear config cache after adding transports:
    php artisan config:clear
    
  • Environment Variables: Use Laravel’s env() helper for dynamic DSNs:
    $dsn = 'slack://' . env('SLACK_WEBHOOK_URL');
    
  • Default Transport: Set a fallback transport in config/notifier.php:
    'default_transport' => 'slack',
    

4. Extension Points

  • Custom Message Types: Extend AbstractMessage for domain-specific messages:
    class InvoiceMessage extends AbstractMessage {
        public function __construct(string $invoiceId, string $amount) {
            parent::__construct('invoice_alert');
            $this->invoiceId = $invoiceId;
            $this->amount = $amount;
        }
    }
    
  • Middleware: Add pre/post-send logic:
    $notifier->addMiddleware(new class implements MiddlewareInterface {
        public function handle(MessageInterface $message, callable $next): void {
            // Pre-send logic
            $next($message);
            // Post-send logic
        }
    });
    
  • Webhook Handling: Use WebhookTransport for incoming notifications (e.g., Slack events):
    $transport = new WebhookTransport('slack', '/slack/webhook');
    $notifier->addTransport('slack_webhook', $transport);
    

5. Performance Tips

  • Batch Processing: Send multiple messages in a single request (e.g., bulk SMS):
    $notifier->send([
        new SmsMessage('+123', 'Hello'),
        new SmsMessage('+124', 'Hello'),
    ]);
    
  • Transport Reuse: Reuse transports across requests to avoid reconnection overhead.
  • Lazy Loading: Load transports only when needed (e.g., in a service provider).

6. Laravel-Specific Tips

  • Service Provider: Bind Notifier in AppServiceProvider:
    public function register() {
        $this->app->singleton(NotifierInterface::class, function ($app) {
            $notifier = new Notifier();
            foreach (config('notifier.transports') as $name => $config) {
                $notifier->add
    
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
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
twbs/bootstrap4
php-http/client-implementation
phpcr/phpcr-implementation
cucumber/gherkin-monorepo
haydenpierce/class-finder
psr/simple-cache-implementation
uri-template/tests