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

Twilio Laravel Package

laravel-notification-channels/twilio

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require laravel-notification-channels/twilio
    

    Publish the config file (optional):

    php artisan vendor:publish --provider="LaravelNotificationChannels\Twilio\TwilioServiceProvider"
    
  2. Configure .env:

    TWILIO_SID=your_account_sid
    TWILIO_TOKEN=your_auth_token
    TWILIO_FROM=+1234567890  # Optional: Default sender number
    
  3. First Use Case: Send a basic SMS notification via a notification class:

    use LaravelNotificationChannels\Twilio\TwilioChannel;
    use LaravelNotificationChannels\Twilio\TwilioMessage;
    
    class SendSmsNotification extends Notification
    {
        public function via($notifiable)
        {
            return [TwilioChannel::class];
        }
    
        public function toTwilio($notifiable)
        {
            return (new TwilioMessage())
                ->content('Hello from Laravel!');
        }
    }
    

    Trigger it in a controller:

    $user->notify(new SendSmsNotification());
    

Implementation Patterns

Usage Patterns

  1. Dynamic Recipients: Use toTwilio() to dynamically set content or recipients:

    public function toTwilio($notifiable)
    {
        return (new TwilioMessage())
            ->content("Your order #{$notifiable->order_id} is confirmed.")
            ->to($notifiable->phone); // Override default recipient
    }
    
  2. Media Attachments: Attach files (e.g., PDFs) to SMS:

    public function toTwilio($notifiable)
    {
        return (new TwilioMessage())
            ->content('Your receipt is attached.')
            ->attach('path/to/receipt.pdf');
    }
    
  3. Channel-Specific Logic: Use via() to conditionally send via Twilio:

    public function via($notifiable)
    {
        return $notifiable->prefers_sms ? [TwilioChannel::class] : [];
    }
    
  4. Batch Sending: Queue notifications for efficiency:

    $user->notify((new SendSmsNotification())->delay(now()->addMinutes(5)));
    

Workflows

  • User Registration: Send a welcome SMS immediately after registration.
  • Password Resets: Integrate with Laravel’s built-in ResetPassword notification.
  • Two-Factor Auth: Send codes via Twilio instead of email.

Integration Tips

  • Twilio Studio: Combine with Twilio Studio flows for complex logic.
  • Webhooks: Use Twilio webhooks to handle delivery status updates (e.g., log failed sends).
  • Fallbacks: Pair with email notifications for critical alerts:
    public function via($notifiable)
    {
        return [MailChannel::class, TwilioChannel::class];
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limits: Twilio enforces rate limits. Monitor usage via the Twilio Debugger. Fix: Implement exponential backoff in retries or use Twilio’s SMS Sync.

  2. Phone Number Formatting: Invalid numbers (e.g., +123) will fail silently. Validate with:

    use Twilio\LibPhp\TwiML\Validator;
    
    if (!Validator::isValidPhoneNumber($phone)) {
        throw new \InvalidArgumentException('Invalid phone number');
    }
    
  3. Environment Variables: Avoid hardcoding TWILIO_SID/TWILIO_TOKEN in code. Use .env or Laravel’s config().

  4. Media Attachments: Large files (>10MB) may fail. Use Twilio’s Media API for larger files.

Debugging

  • Logs: Enable Twilio debug logs in config/twilio.php:
    'debug' => env('TWILIO_DEBUG', false),
    
  • Twilio Console: Check the Twilio Debugger for failed requests.
  • Mocking: Use Mockery to test locally:
    $this->partialMock(TwilioClient::class, function ($mock) {
        $mock->shouldReceive('messages')->andReturnSelf();
        $mock->shouldReceive('create')->andReturn(new Twilio\Rest\Api\V2010\Account\MessageContext());
    });
    

Config Quirks

  1. Default from Number: If omitted, Twilio uses a random number from your account. Specify a dedicated number in .env:

    TWILIO_FROM=+1234567890
    
  2. Message Length: SMS is limited to 1600 characters (360 chars per segment). Long messages auto-segment but cost more. Tip: Use TwilioMessage::content() with plain text for best results.

  3. Timeouts: Twilio’s API timeout is 30 seconds. For long-running tasks, use queues:

    $user->notify(new SendSmsNotification())->onQueue('sms');
    

Extension Points

  1. Custom Twilio Client: Bind a custom TwilioClient instance in a service provider:

    $this->app->singleton(TwilioClient::class, function () {
        return new TwilioClient(
            config('services.twilio.sid'),
            config('services.twilio.token'),
            ['httpClient' => new GuzzleHttp\Client(['timeout' => 60])]
        );
    });
    
  2. Event Listeners: Listen for TwilioMessageSent events to log or process responses:

    use LaravelNotificationChannels\Twilio\Events\TwilioMessageSent;
    
    public function handle(TwilioMessageSent $event)
    {
        Log::info('SMS sent to ' . $event->message->to, ['sid' => $event->message->sid]);
    }
    
  3. Channel Extensions: Extend TwilioChannel to add custom logic:

    class CustomTwilioChannel extends TwilioChannel
    {
        public function send($notifiable, $message)
        {
            // Pre-process message (e.g., add tracking ID)
            $message->content = "[ID: {$notifiable->id}] " . $message->content;
            parent::send($notifiable, $message);
        }
    }
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
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