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 lets your app send notifications through multiple channels like email, SMS, chat, and more. It provides a unified API, integrates with many third-party providers, and supports routing, transports, and message formatting for flexible delivery.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the Package

    composer require symfony/notifier
    

    For Laravel-specific integrations (e.g., Mailer transport), use:

    composer require symfony/mailer
    
  2. Configure Transports Define transports in config/services.php (or a dedicated notifier.php config file):

    'notifier' => [
        'dsn' => [
            'default' => 'smtp://user:pass@smtp.example.com:587',
            'slack' => 'slack://token?channel=general',
            'twilio' => 'sms://account_sid:auth_token@twilio.com?from=+1234567890',
        ],
    ],
    

    Or use environment variables (recommended):

    NOTIFIER_DSN_DEFAULT=smtp://user:pass@smtp.example.com:587
    NOTIFIER_DSN_SLACK=slack://token?channel=general
    
  3. First Notification Send an email via the CLI or a controller:

    use Symfony\Component\Notifier\Notifier;
    use Symfony\Component\Notifier\Bridge\Mailer\MailerTransport;
    
    $notifier = new Notifier([
        new MailerTransport($mailer), // Laravel's built-in mailer
    ]);
    
    $notifier->send(
        new Email('user@example.com', 'Welcome!', 'Hello, this is your first notification.')
    );
    
  4. Key Starting Points


Implementation Patterns

Core Workflows

1. Channel-Agnostic Notification Dispatch

Use the Notifier class to send messages across multiple channels with a single call:

$notifier = new Notifier([
    new MailerTransport($mailer),
    new SlackTransport('token', 'channel'),
    new TwilioTransport('account_sid', 'auth_token', 'from'),
]);

$notifier->send(
    new Email('user@example.com', 'Alert', 'Your action is required.'),
    new SlackMessage('team', '🚨 Action required: ' . $context),
    new Sms('+1234567890', 'Your code: ' . $otp)
);

2. Dynamic Recipient Resolution

Fetch recipients from Laravel models (e.g., User) and attach context:

$user = User::find(1);
$notifier->send(
    new Email($user->email, 'Your Order Update', view('emails.order_update', ['order' => $user->orders->latest()]))
        ->priority(Email::PRIORITY_HIGH)
        ->replyTo('support@example.com')
);

3. Event-Driven Notifications

Trigger notifications from Laravel events (e.g., OrderShipped):

// In EventServiceProvider
protected $listen = [
    OrderShipped::class => [NotifyOrderShipped::class],
];

// Notification handler
class NotifyOrderShipped implements ShouldQueue {
    public function handle(OrderShipped $event) {
        $notifier = app(Notifier::class);
        $notifier->send(
            new Email($event->order->user->email, 'Order Shipped', view('emails.shipped', ['order' => $event->order]))
        );
    }
}

4. Rich Message Formatting

Leverage Markdown, HTML, or interactive elements (e.g., Slack buttons):

// Slack message with buttons
$slackMessage = new SlackMessage('team', 'Approve this?')
    ->addButton('Approve', 'https://app.example.com/approve?id=123')
    ->addButton('Reject', 'https://app.example.com/reject?id=123');

$notifier->send($slackMessage);

// Email with inline HTML
$email = new Email('user@example.com', 'Invoice', '<h1>Your Invoice</h1><p>Total: $99.99</p>');

5. Asynchronous Processing

Use Laravel Queues to avoid blocking requests:

$notifier->send(
    new Email('user@example.com', 'Welcome')
        ->toQueue() // Dispatches to queue
);

Or wrap the Notifier in a job:

class SendWelcomeEmail implements ShouldQueue {
    public function handle() {
        $notifier = new Notifier([new MailerTransport($mailer)]);
        $notifier->send(new Email('user@example.com', 'Welcome'));
    }
}

Laravel-Specific Integrations

1. Mailer Transport

Use Laravel’s built-in mailer with Symfony Notifier:

$notifier = new Notifier([
    new MailerTransport($mailer), // Inject Laravel's \Illuminate\Mail\Mailer
]);

2. Queue Integration

Combine with Laravel Queues for async delivery:

$notifier = new Notifier([new MailerTransport($mailer)]);
$notifier->send(
    new Email('user@example.com', 'Hello')
        ->toQueue('notifications') // Custom queue name
);

3. Service Provider Setup

Bind the Notifier to Laravel’s container in AppServiceProvider:

public function register() {
    $this->app->singleton(Notifier::class, function ($app) {
        return new Notifier([
            new MailerTransport($app->make(\Illuminate\Mail\Mailer::class)),
            new SlackTransport(env('SLACK_TOKEN'), env('SLACK_CHANNEL')),
        ]);
    });
}

4. View-Based Emails

Use Laravel views with Notifier:

$email = new Email('user@example.com', 'Welcome')
    ->html(view('emails.welcome', ['name' => 'John']))
    ->text(view('emails.welcome_text', ['name' => 'John']));

Advanced Patterns

1. Transport Factories

Dynamically create transports based on config:

$transport = TransportFactory::get($dsn);
$notifier = new Notifier([$transport]);

2. Recipient Groups

Send to multiple recipients with a single call:

$notifier->send(
    new Email(['user1@example.com', 'user2@example.com'], 'Team Update', 'Hello team!')
);

3. Attachment Handling

Add files to emails/SMS:

$email = new Email('user@example.com', 'Your File')
    ->attachment(new \Symfony\Component\Mime\Part\FilePart('path/to/file.pdf'));

4. Webhook Responses

Handle incoming webhooks (e.g., Slack events):

use Symfony\Component\Notifier\Bridge\Slack\SlackWebhook;

$webhook = new SlackWebhook($request->getContent());
if ($webhook->isValid()) {
    $event = $webhook->getEvent();
    // Process event (e.g., store reaction, update DB)
}

5. Custom Transports

Extend for proprietary APIs:

use Symfony\Component\Notifier\Transport\TransportInterface;

class CustomTransport implements TransportInterface {
    public function __send(NotificationInterface $notification, array $failedRecipients = []): void {
        // Implement custom logic (e.g., HTTP request to your API)
    }
}

Gotchas and Tips

Common Pitfalls

1. DSN Configuration

  • Issue: Incorrect DSN format (e.g., missing ? for options).
    # Wrong: Missing `?` before options
    NOTIFIER_DSN_SLACK=slack://tokenchannel=general
    
    # Correct:
    NOTIFIER_DSN_SLACK=slack://token?channel=general
    
  • Tip: Use TransportFactory::get() to validate DSNs early:
    $transport = TransportFactory::get(env('NOTIFIER_DSN_SLACK'));
    

2. Recipient Validation

  • Issue: Invalid email/SMS numbers cause silent failures.
  • Tip: Validate recipients before sending:
    $email = new Email('invalid-email', 'Test');
    if (!$email->isValid()) {
        throw new \InvalidArgumentException('Invalid recipient');
    }
    

3. Async Delivery Quirks

  • Issue: Queued
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/entity-migrator
codraw/doctrine-extra
codraw/aws-tool-kit
codraw/validator
codraw/workflow
codraw/open-api
codraw/cron-job
codraw/process
codraw/log
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