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 Notification Laravel Package

websms/laravel-notification

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require websms/laravel-notification
    

    Register the service provider in config/app.php:

    'providers' => [
        Websms\LaravelNotification\WebSmsServiceProvider::class,
    ],
    
  2. Configure Credentials: Add WebSMS credentials to .env:

    WEBSMS_USERNAME=your_username
    WEBSMS_PASSWORD=your_password
    WEBSMS_SENDNUMBER=your_sender_number
    

    Ensure config/services.php references these:

    'websms' => [
        'username' => env('WEBSMS_USERNAME'),
        'password' => env('WEBSMS_PASSWORD'),
        'sendNumber' => env('WEBSMS_SENDNUMBER'),
    ],
    
  3. First Notification: Create a notification class (e.g., App\Notifications\SendSmsNotification) and define the via() and toSms() methods:

    use Websms\LaravelNotification\Channels\WebSmsChannel;
    use Websms\LaravelNotification\Messages\WebSmsMessage;
    
    public function via($notifiable) {
        return [WebSmsChannel::class];
    }
    
    public function toSms($notifiable) {
        $message = new WebSmsMessage();
        $message->setFrom(env('WEBSMS_SENDNUMBER'))
                ->setTo($notifiable->routeNotificationFor('sms'))
                ->setMessage('Hello from Laravel!');
        return $message;
    }
    
  4. Trigger the Notification:

    $user = User::find(1);
    $user->notify(new SendSmsNotification());
    

Implementation Patterns

Core Workflow

  1. Notification Routing: Define the routeNotificationFor('sms') method in your User model to specify the recipient’s phone number:

    public function routeNotificationForSms() {
        return $this->phone_number; // e.g., '27821234567'
    }
    
  2. Dynamic Message Handling: Use the toSms() method to customize messages per recipient or context:

    public function toSms($notifiable) {
        $message = new WebSmsMessage();
        $message->setTo($notifiable->routeNotificationFor('sms'))
                ->setMessage("Your verification code is: {$this->code}");
        return $message;
    }
    
  3. Batch Notifications: Leverage Laravel’s Notification facade to send to multiple users:

    $users = User::where('is_active', true)->get();
    Notification::send($users, new SendSmsNotification());
    
  4. Queueing for Reliability: Queue notifications to avoid timeouts or failures:

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

Integration Tips

  • Logging Failures: Override the failed() method in your notification to log SMS failures:

    public function failed(Notification $notification, array $channels) {
        \Log::error("SMS failed for {$notification->notifiable->email}");
    }
    
  • Testing: Use Laravel’s NotificationFake for unit tests:

    $this->withoutExceptionHandling();
    Notification::fake();
    $user->notify(new SendSmsNotification());
    Notification::assertSentTo($user, SendSmsNotification::class);
    
  • Customizing the Channel: Extend WebSmsChannel to add retries or logging:

    class CustomWebSmsChannel extends WebSmsChannel {
        public function send($notifiable, $message) {
            try {
                parent::send($notifiable, $message);
            } catch (\Exception $e) {
                \Log::error("SMS send failed: " . $e->getMessage());
                throw $e;
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • Last updated in 2019, so compatibility with newer Laravel versions (9.x/10.x) may require adjustments (e.g., Notification facade changes).
    • Fix: Check for breaking changes in Laravel’s upgrade guide.
  2. No Built-in Retries:

    • The package lacks retry logic for failed SMS sends. Use Laravel’s queue retries:
    $user->notify(new SendSmsNotification())->onQueue('sms')->afterCommit();
    
  3. Sender Number Validation:

    • WebSMS may reject invalid sender numbers (e.g., non-E.164 format). Validate in toSms():
    $sender = env('WEBSMS_SENDNUMBER');
    if (!preg_match('/^\+[0-9]{10,15}$/', $sender)) {
        throw new \Exception("Invalid sender number format");
    }
    
  4. Rate Limiting:

    • WebSMS may throttle requests. Implement exponential backoff in a custom channel:
    use Illuminate\Support\Facades\Http;
    
    public function send($notifiable, $message) {
        $response = Http::retry(3, 100)->post('https://api.websms.com/send', [
            'username' => config('services.websms.username'),
            'password' => config('services.websms.password'),
            'to' => $message->getTo(),
            'message' => $message->getMessage(),
        ]);
    }
    

Debugging Tips

  1. Enable Debug Logging: Add to config/logging.php:

    'channels' => [
        'websms' => [
            'driver' => 'single',
            'path' => storage_path('logs/websms.log'),
            'level' => 'debug',
        ],
    ],
    

    Then log requests/responses in the channel:

    \Log::debug('SMS Request:', [
        'to' => $message->getTo(),
        'message' => $message->getMessage(),
    ]);
    
  2. Mocking WebSMS API: Use Laravel’s HTTP client to mock responses in tests:

    Http::fake([
        'https://api.websms.com/send' => Http::response('OK', 200),
    ]);
    
  3. Environment-Specific Config: Use config/services.php overrides for different environments (e.g., staging/production):

    if (app()->environment('staging')) {
        config(['services.websms.sendNumber' => '1234567890']);
    }
    

Extension Points

  1. Custom Message Class: Extend WebSmsMessage to add metadata (e.g., campaign IDs):

    class ExtendedWebSmsMessage extends WebSmsMessage {
        public function setCampaignId($id) {
            $this->campaign_id = $id;
            return $this;
        }
    }
    
  2. Webhook Integration: Add a WebhookHandler to process delivery reports from WebSMS:

    Route::post('/websms/webhook', function (Request $request) {
        \Log::info('WebSMS Webhook:', $request->all());
        // Update notification status in DB
    });
    
  3. Template Engine: Use Blade templates for SMS messages:

    public function toSms($notifiable) {
        $message = new WebSmsMessage();
        $message->setMessage(view('notifications.sms_template', ['user' => $notifiable])->render());
        return $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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky