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

djunehor/laravel-sms

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require djunehor/laravel-sms
    

    Publish the config file:

    php artisan vendor:publish --provider="Djunehor\LaravelSms\LaravelSmsServiceProvider" --tag="config"
    

    Add the SMS facade to your config/app.php:

    'aliases' => [
        // ...
        'SMS' => Djunehor\LaravelSms\Facades\SMS::class,
    ],
    
  2. Configure Provider: Edit config/sms.php and set your preferred provider (e.g., twilio, nexmo, clickatell). Example for Twilio:

    'twilio' => [
        'account_sid' => env('TWILIO_SID'),
        'auth_token' => env('TWILIO_TOKEN'),
        'from' => env('TWILIO_FROM'),
    ],
    
  3. First Use Case: Send an SMS via the facade:

    use SMS;
    
    SMS::send('twilio', '+1234567890', 'Hello from Laravel!');
    

    Or use a queueable job:

    php artisan make:job SendSmsJob
    
    // In SendSmsJob.php
    public function handle()
    {
        SMS::send('twilio', '+1234567890', 'Hello from a job!');
    }
    

Implementation Patterns

Core Workflows

  1. Provider-Specific Configuration:

    • Use environment variables for sensitive data (e.g., TWILIO_SID, NEXMO_KEY).
    • Override default config in config/sms.php per environment (e.g., sms.php for staging vs. production).
  2. Sending SMS:

    • Facade Method:
      SMS::send($provider, $to, $message, $options = []);
      
      Example with options (e.g., Twilio media URL):
      SMS::send('twilio', '+1234567890', 'Check this out!', [
          'media_url' => 'https://example.com/image.jpg'
      ]);
      
    • Queueable Jobs: Useful for async processing. Example:
      dispatch(new SendSmsJob('nexmo', '+1234567890', 'Async message'));
      
  3. Custom Providers: Extend the base Provider class to integrate with unsupported services:

    namespace App\Providers;
    
    use Djunehor\LaravelSms\Providers\Provider;
    
    class CustomProvider extends Provider
    {
        public function send($to, $message, array $options = [])
        {
            // Custom logic (e.g., HTTP request to your SMS API)
            return $this->client->send($to, $message);
        }
    }
    

    Register in config/sms.php:

    'providers' => [
        'custom' => \App\Providers\CustomProvider::class,
    ],
    
  4. Logging and Retries:

    • Enable Laravel’s queue worker with retries for failed jobs:
      php artisan queue:work --sleep=3 --tries=3
      
    • Log failures via SMS::fail() or use Laravel’s default job failure channels.
  5. Testing:

    • Use a mock provider for unit tests:
      SMS::setProvider('mock');
      SMS::send('mock', '+1234567890', 'Test message');
      
    • Assert sent messages in tests:
      $this->assertEquals('Test message', SMS::getLastMessage());
      

Gotchas and Tips

Common Pitfalls

  1. Provider-Specific Quirks:

    • Twilio: Ensure from number is verified in Twilio console. Use E.164 format for phone numbers (e.g., +1234567890).
    • Nexmo: Validate API key and secret. Some regions require specific sender IDs.
    • Clickatell: API URL may change; check their docs for the latest endpoint.
  2. Rate Limits:

    • Most providers throttle requests. Implement exponential backoff in custom providers or use Laravel’s retry-after middleware for queues.
  3. Character Limits:

    • SMS messages are typically limited to 160 characters (GSM-7 encoding). Use Unicode (UTF-16) for longer messages (70 chars per segment). Example:
      SMS::send('twilio', '+1234567890', Str::of($message)->limit(150));
      
  4. Environment Mismatches:

    • Ensure config/sms.php points to the correct provider for each environment (e.g., mock for local, twilio for production).
  5. Queue Stuck Jobs:

    • Failed jobs may pile up if the provider API is unreachable. Monitor queues with:
      php artisan queue:failed-table
      
    • Reprocess failed jobs:
      php artisan queue:retry <job-id>
      

Debugging Tips

  1. Enable Logging: Add to config/sms.php:

    'log' => true,
    

    Check storage/logs/laravel.log for SMS-related entries.

  2. Provider-Specific Errors:

    • Twilio: Check http_errors in logs for HTTP 4xx/5xx responses.
    • Nexmo: Validate message-id in responses to confirm delivery.
  3. Network Issues:

    • Use curl to test provider APIs directly:
      curl -X POST https://api.twilio.com/2010-04-01/Accounts/{SID}/Messages.json \
           -d "To=+1234567890" \
           -d "From=+1987654321" \
           -d "Body=Test" \
           -u {SID}:{TOKEN}
      

Extension Points

  1. Custom Responses: Extend the Provider class to handle provider-specific responses (e.g., Nexmo’s message-uuid):

    public function send($to, $message, array $options = [])
    {
        $response = $this->client->send($to, $message);
        return [
            'success' => true,
            'message_id' => $response->message_uuid ?? null,
        ];
    }
    
  2. Webhook Handling: For delivery receipts, create a route to handle provider webhooks (e.g., Twilio’s MessageStatus):

    Route::post('/sms/webhook', function (Request $request) {
        SMS::handleWebhook($request->all());
    });
    
  3. Fallback Providers: Implement a fallback chain in config/sms.php:

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

    The package will attempt providers in order until one succeeds.

  4. Template Messages: Use Blade templates for dynamic SMS content:

    $message = view('emails.sms-template', ['name' => 'John'])->render();
    SMS::send('twilio', '+1234567890', $message);
    
  5. Batch Sending: For bulk SMS, loop through recipients and use batch processing:

    foreach ($recipients as $phone) {
        SMS::send('twilio', $phone, 'Batch message')->onQueue('sms');
    }
    

    Process queues in parallel with Laravel Horizon or multiple queue workers.

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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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