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

Sms Bundle Laravel Package

chewbacco/sms-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require chewbacco/sms-bundle
    

    Add the bundle to config/bundles.php (Symfony) or register the service provider in config/app.php (Laravel):

    Chewbacco\SmsBundle\ChewbaccoSmsBundle::class,
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Chewbacco\SmsBundle\ChewbaccoSmsBundle" --tag="config"
    

    Update config/sms.php with your provider credentials (e.g., Twilio, AWS SNS, or a custom gateway).

  3. First Use Case: Sending a Basic SMS Inject the SmsService into a controller or service:

    use Chewbacco\SmsBundle\Services\SmsService;
    
    public function sendWelcomeSms(SmsService $smsService)
    {
        $smsService->send([
            'to' => '+1234567890',
            'body' => 'Welcome to our platform!'
        ]);
    }
    
  4. Verify Provider Check config/sms.php for the active provider and its configuration. Example for Twilio:

    'providers' => [
        'twilio' => [
            'account_sid' => env('TWILIO_SID'),
            'auth_token' => env('TWILIO_TOKEN'),
            'from' => '+1234567890',
        ],
    ],
    

    Set the default provider in default_provider: twilio.


Implementation Patterns

Core Workflows

  1. Sending SMS

    • Basic Send:
      $smsService->send(['to' => '+1234567890', 'body' => 'Hello!']);
      
    • With Options:
      $smsService->send([
          'to' => '+1234567890',
          'body' => 'Hello!',
          'from' => '+1987654321', // Override default 'from'
          'provider' => 'aws',    // Specify provider
      ]);
      
    • Batch Send:
      $smsService->sendBatch([
          ['to' => '+1234567890', 'body' => 'Message 1'],
          ['to' => '+1987654321', 'body' => 'Message 2'],
      ]);
      
  2. Event-Driven SMS Listen for model events (e.g., UserRegistered) and trigger SMS:

    use Chewbacco\SmsBundle\Events\SmsSent;
    
    public function handleUserRegistered()
    {
        event(new SmsSent([
            'to' => auth()->user()->phone,
            'body' => 'Your account is ready!',
        ]));
    }
    
  3. Queueing SMS Dispatch SMS jobs to a queue (requires queue driver in .env):

    $smsService->dispatch([
        'to' => '+1234567890',
        'body' => 'Queued message!',
    ]);
    

Integration Tips

  • Validation: Validate phone numbers before sending (e.g., using libphonenumber).
    use giggsey\LibPhonenumber\PhoneNumberBundle\Validator\Constraints\PhoneNumber;
    
  • Logging: Enable SMS logs in config/sms.php:
    'log_sent_sms' => true,
    
  • Testing: Mock SmsService in tests:
    $this->mock(SmsService::class)->shouldReceive('send')->once();
    

Gotchas and Tips

Pitfalls

  1. Provider Configuration

    • Issue: Forgetting to set default_provider in config/sms.php throws RuntimeException.
    • Fix: Always define a default or specify a provider per call.
    • Debug: Check storage/logs/laravel.log for missing credentials.
  2. Phone Number Format

    • Issue: Invalid phone numbers (e.g., 1234567890 without +) may fail silently or return errors.
    • Fix: Use a library like libphonenumber to validate/format numbers:
      $phone = PhoneNumber::parse($rawPhone, 'US');
      $formatted = $phone->formatE164();
      
  3. Rate Limits

    • Issue: Providers like Twilio have rate limits. Unhandled exceptions may crash your app.
    • Fix: Implement retry logic with retry middleware or queue failed jobs:
      $smsService->sendWithRetry(['to' => '+1234567890', 'body' => 'Message'], 3);
      
  4. Environment Variables

    • Issue: Hardcoding credentials in config/sms.php instead of using .env.
    • Fix: Use Laravel’s .env for sensitive data:
      'account_sid' => env('TWILIO_SID'),
      

Debugging

  • Enable Debug Mode: Set 'debug' => true in config/sms.php to log provider responses.
  • Check Queue Workers: If using queues, ensure workers are running:
    php artisan queue:work
    
  • Provider-Specific Errors:
    • Twilio: Check Twilio Debugger.
    • AWS SNS: Verify IAM permissions and region in config/sms.php.

Extension Points

  1. Custom Providers Extend the bundle by creating a new provider class:

    namespace App\Providers;
    
    use Chewbacco\SmsBundle\Contracts\SmsProviderInterface;
    
    class CustomProvider implements SmsProviderInterface {
        public function send(array $message) {
            // Custom logic (e.g., HTTP API call)
        }
    }
    

    Register it in config/sms.php:

    'providers' => [
        'custom' => [
            'class' => App\Providers\CustomProvider::class,
            'config' => [...],
        ],
    ],
    
  2. Events and Listeners Extend functionality by listening to SmsSent or SmsFailed events:

    // Event listener
    public function onSmsSent(SmsSent $event) {
        Log::info('SMS sent to: ' . $event->getMessage()['to']);
    }
    
  3. Middleware Add middleware to modify messages before sending:

    $smsService->addMiddleware(function ($message) {
        $message['body'] .= "\nPowered by ChewbaccoSmsBundle";
        return $message;
    });
    

Performance Tips

  • Batch Processing: Use sendBatch() for bulk SMS to reduce API calls.
  • Caching: Cache frequently used provider configurations (e.g., Twilio credentials).
  • Async Validation: Validate phone numbers asynchronously to avoid blocking the request.
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui