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

Laravel Sms Laravel Package

mr-rijal/laravel-sms

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mr-rijal/laravel-sms
    

    Publish the config file:

    php artisan vendor:publish --provider="MrRijal\LaravelSms\SmsServiceProvider"
    
  2. Configuration: Edit config/sms.php to define your preferred gateway (e.g., nexmo, twilio, aws-sns) and credentials.

  3. First Use Case: Send a basic SMS via a controller:

    use MrRijal\LaravelSms\Facades\Sms;
    
    public function sendWelcomeSms()
    {
        Sms::send([
            'to' => '1234567890',
            'body' => 'Welcome to our platform!'
        ]);
    }
    
  4. Key Files:

    • config/sms.php: Gateway and channel configurations.
    • app/Providers/SmsServiceProvider.php: Extend or override default behavior.
    • routes/sms.php: Predefined routes for testing (if enabled).

Implementation Patterns

Core Workflows

  1. Gateway-Specific Configuration: Define gateways in config/sms.php:

    'gateways' => [
        'nexmo' => [
            'key' => env('NEXMO_KEY'),
            'secret' => env('NEXMO_SECRET'),
            'from' => env('NEXMO_FROM'),
        ],
        'twilio' => [
            'sid' => env('TWILIO_SID'),
            'token' => env('TWILIO_TOKEN'),
            'from' => env('TWILIO_FROM'),
        ],
    ],
    
  2. Sending SMS:

    • Basic Send:
      Sms::send(['to' => '1234567890', 'body' => 'Hello']);
      
    • With Gateway:
      Sms::send(['to' => '1234567890', 'body' => 'Hello'], 'nexmo');
      
    • Async with Queue:
      Sms::queue(['to' => '1234567890', 'body' => 'Hello']);
      
  3. Templates and Variables: Use named templates in config/sms.php:

    'templates' => [
        'welcome' => [
            'body' => 'Hi {name}, welcome to {app}!',
        ],
    ],
    

    Send with variables:

    Sms::send([
        'to' => '1234567890',
        'template' => 'welcome',
        'variables' => ['name' => 'John', 'app' => 'MyApp'],
    ]);
    
  4. Events and Listeners: Listen for SMS events (e.g., SmsSent, SmsFailed):

    // In EventServiceProvider
    protected $listen = [
        'MrRijal\LaravelSms\Events\SmsSent' => [
            'App\Listeners\LogSmsSent',
        ],
    ];
    
  5. Testing: Use the log channel for testing:

    'channels' => [
        'log' => [
            'driver' => 'log',
        ],
    ],
    

    Then send via:

    Sms::send(['to' => '1234567890', 'body' => 'Test'], 'log');
    

Integration Tips

  1. Queue Management: Ensure your queue worker is running:

    php artisan queue:work
    

    For large volumes, consider batching or delayed queues.

  2. Fallback Gateways: Configure fallback gateways in config/sms.php:

    'fallback' => ['nexmo', 'twilio'],
    

    The package will attempt secondary gateways if the primary fails.

  3. Logging: Enable logging in config/sms.php:

    'log' => true,
    

    Logs will appear in storage/logs/laravel-sms.log.

  4. API Integration: For custom APIs, create a custom gateway:

    // app/Providers/SmsServiceProvider.php
    public function register()
    {
        $this->app->extend('sms.gateways', function ($gateways) {
            $gateways['custom'] = new \App\Sms\CustomGateway();
            return $gateways;
        });
    }
    
  5. Rate Limiting: Use Laravel's rate limiting middleware for SMS endpoints:

    Route::middleware(['throttle:60,1'])->group(function () {
        // SMS-related routes
    });
    

Gotchas and Tips

Pitfalls

  1. Environment Variables: Ensure all gateway credentials are set in .env before sending. Missing keys will throw InvalidArgumentException.

  2. Queue Stuck Jobs: If jobs are stuck, check the queue table for failed jobs and retry manually:

    php artisan queue:retry all
    
  3. Character Limits: Some gateways (e.g., Twilio) enforce strict character limits (~1600 chars for Unicode). Test long messages in staging.

  4. Timeouts: Gateway timeouts (default: 30s) may cause jobs to fail silently. Increase in config/sms.php:

    'timeout' => 60,
    
  5. International Numbers: Ensure numbers are in E.164 format (e.g., +1234567890). Use the e164 package for validation:

    use E164\PhoneNumber;
    $number = PhoneNumber::parse('1234567890')->formatE164();
    

Debugging

  1. Enable Debug Mode: Set debug: true in config/sms.php to log raw API responses:

    'debug' => env('APP_DEBUG', false),
    
  2. Check Logs: Inspect storage/logs/laravel-sms.log for gateway-specific errors (e.g., Twilio API rejections).

  3. Gateway-Specific Issues:

    • Nexmo: Ensure the from number is verified in your Nexmo dashboard.
    • Twilio: Check the from number is purchased in your Twilio console.
    • AWS SNS: Verify IAM permissions and SNS topic subscriptions.
  4. Common Errors:

    • SmsException: Catch and handle gateway-specific exceptions:
      try {
          Sms::send([...]);
      } catch (\MrRijal\LaravelSms\Exceptions\SmsException $e) {
          Log::error('SMS failed: ' . $e->getMessage());
      }
      

Extension Points

  1. Custom Gateways: Extend the MrRijal\LaravelSms\Contracts\Gateway interface:

    class CustomGateway implements Gateway
    {
        public function send($message)
        {
            // Custom logic
        }
    }
    

    Register in SmsServiceProvider.

  2. Override Default Behavior: Bind the SmsManager interface to a custom implementation:

    $this->app->bind(\MrRijal\LaravelSms\Contracts\SmsManager::class, function ($app) {
        return new \App\Sms\CustomSmsManager($app);
    });
    
  3. Add Custom Fields: Extend the Message class:

    class CustomMessage extends \MrRijal\LaravelSms\Message
    {
        protected $customField;
    
        public function setCustomField($value)
        {
            $this->customField = $value;
            return $this;
        }
    }
    

    Update the SmsManager to handle the new field.

  4. Webhooks: Listen for gateway webhooks (e.g., Twilio's message.created) to update delivery status:

    Route::post('/sms/webhook', [SmsWebhookController::class, 'handle']);
    

Performance Tips

  1. Batch Processing: Use Laravel's chunk method for bulk SMS:

    User::chunk(100, function ($users) {
        foreach ($users as $user) {
            Sms::queue(['to' => $user->phone, 'body' => 'Your message']);
        }
    });
    
  2. Cache Gateways: Cache gateway instances to reduce overhead:

    $this->app->singleton(\MrRijal\LaravelSms\Contracts\Gateway::class, function ($app) {
        return new \MrRijal\LaravelSms\Gateways\NexmoGateway(config('sms.gateways.nexmo'));
    });
    
  3. Async Validation: Validate phone numbers asynchronously to

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