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

Sdk Laravel Package

twilio/sdk

Official Twilio PHP SDK for interacting with Twilio APIs. Send SMS/WhatsApp, place calls, manage messaging, Verify, and other Twilio services from PHP apps. Composer-ready, supports PHP 7.2–8.4, with docs and examples.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require twilio/sdk
    

    Add to config/services.php (Laravel convention):

    'twilio' => [
        'account_sid' => env('TWILIO_SID'),
        'auth_token' => env('TWILIO_TOKEN'),
        'region' => env('TWILIO_REGION', 'us1'),
    ],
    
  2. Service Provider: Register in config/app.php:

    'providers' => [
        // ...
        Twilio\Laravel\TwilioServiceProvider::class,
    ],
    
  3. First Use Case: Send an SMS via a Laravel controller:

    use Twilio\Laravel\Facades\Twilio;
    
    public function sendSms()
    {
        $message = Twilio::message('+15558675309', 'Hello from Laravel!');
        $message->send();
        return response()->json(['success' => true]);
    }
    

Implementation Patterns

Core Workflows

  1. Service Facade Integration: Use Laravel's service container to inject Twilio\Laravel\Facades\Twilio:

    public function __construct(Twilio $twilio) {
        $this->twilio = $twilio;
    }
    
  2. Event-Driven Patterns: Handle Twilio webhooks via Laravel routes:

    Route::post('/twilio-webhook', [TwilioWebhookController::class, 'handle']);
    

    Use Twilio\Laravel\TwilioWebhookRequest to validate and parse payloads:

    $request = new TwilioWebhookRequest();
    $request->handle($this->request);
    
  3. Batch Processing: Stream large datasets (e.g., call logs) with pagination:

    $calls = Twilio::calls()->stream(['status' => 'completed'], 100, 20);
    foreach ($calls as $call) {
        // Process each call
    }
    
  4. TwiML Generation: Dynamically generate TwiML responses in routes:

    return response(Twilio::response()->say('Welcome!')->generate(), 200)
        ->header('Content-Type', 'text/xml');
    

Integration Tips

  • Environment Variables: Store credentials in .env (never hardcode).
  • Middleware: Use Laravel middleware to validate Twilio signatures:
    public function handle($request, Closure $next) {
        $request->validateTwilioSignature();
        return $next($request);
    }
    
  • Queue Jobs: Offload long-running tasks (e.g., sending bulk SMS):
    SendSmsJob::dispatch('+15558675309', 'Your message');
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting: Twilio enforces rate limits. Use exponential backoff in retries:

    try {
        $message->send();
    } catch (TwilioException $e) {
        if ($e->getCode() === 429) {
            sleep(2); // Retry after delay
        }
    }
    
  2. Timeouts: Default HTTP client timeout is 30s. Adjust for long operations:

    $client = new Twilio\Rest\Client($sid, $token);
    $client->setHttpClient(new CurlClient(['timeout' => 60]));
    
  3. TwiML Validation: Invalid TwiML throws TwimlException. Validate dynamically:

    try {
        $response = Twilio::response()->dial()->conference('room123');
        $response->validate(); // Explicit check
    } catch (TwimlException $e) {
        Log::error($e->getMessage());
    }
    

Debugging

  • Log Requests: Enable debug logging via config:

    'twilio' => [
        'log_level' => 'debug',
    ],
    

    Or programmatically:

    Twilio::setLogLevel('debug');
    
  • Inspect Responses: Access raw HTTP data:

    $lastResponse = Twilio::getLastResponse();
    Log::debug($lastResponse->getBody());
    

Extension Points

  1. Custom HTTP Clients: Replace the default client for advanced use cases (e.g., Guzzle):

    $client = new Twilio\Rest\Client($sid, $token, new GuzzleHttpClient());
    
  2. Middleware Hooks: Extend Twilio requests/responses via Laravel middleware:

    public function handle($request, Closure $next) {
        $request->setHeader('X-Custom-Header', 'value');
        return $next($request);
    }
    
  3. Event Listeners: Subscribe to Twilio events (e.g., message status changes):

    event(new MessageStatusChanged($message));
    

Laravel-Specific Quirks

  • Service Binding: Ensure the TwilioServiceProvider is registered before use. If not, bind manually:

    $this->app->bind('twilio', function ($app) {
        return new Twilio\Rest\Client(
            $app['config']['services.twilio.account_sid'],
            $app['config']['services.twilio.auth_token'],
            null,
            $app['config']['services.twilio.region']
        );
    });
    
  • Testing: Use mocks for unit tests:

    $mockClient = Mockery::mock(Twilio\Rest\Client::class);
    $this->app->instance(Twilio\Rest\Client::class, $mockClient);
    
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
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
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