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

kavenegar/laravel-notification

Laravel 5.3/5.4 notification channel for sending SMS via Kavenegar. Install via Composer, configure API key (and optional sender) in services.php, then use KavenegarChannel in notifications and routeNotificationForSms on your notifiable model.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require kavenegar/laravel-notification
    

    Register the service provider in config/app.php:

    Kavenegar\LaravelNotification\KavenegarServiceProvider::class
    
  2. Configure API Key: Add your Kavenegar credentials to .env:

    KAVENEGAR_API_KEY=your_api_key_here
    KAVENEGAR_SENDER=your_sender_number
    

    Ensure config/services.php includes:

    'kavenegar' => [
        'key' => env('KAVENEGAR_API_KEY'),
        'sender' => env('KAVENEGAR_SENDER'),
    ],
    
  3. First Use Case: Create a notification class (e.g., app/Notifications/SendVerificationCode.php):

    use Kavenegar\LaravelNotification\KavenegarChannel;
    use Illuminate\Notifications\Notification;
    
    class SendVerificationCode extends Notification
    {
        protected $code;
    
        public function __construct($code)
        {
            $this->code = $code;
        }
    
        public function via($notifiable)
        {
            return [KavenegarChannel::class];
        }
    
        public function toSMS($notifiable)
        {
            return "Your verification code is: {$this->code}";
        }
    }
    

    Dispatch the notification in your controller:

    use App\Notifications\SendVerificationCode;
    
    $user->notify(new SendVerificationCode('123456'));
    

Implementation Patterns

Usage Patterns

  1. Dynamic SMS Content: Use the toSMS() method to dynamically generate messages based on user data or context:

    public function toSMS($notifiable)
    {
        return "Hello {$notifiable->name}, your order #{$this->orderId} is confirmed!";
    }
    
  2. Multi-Channel Notifications: Combine Kavenegar with other channels (e.g., Mail) for hybrid notifications:

    public function via($notifiable)
    {
        return [MailChannel::class, KavenegarChannel::class];
    }
    
  3. Queueing Notifications: Leverage Laravel’s queue system to send SMS asynchronously:

    $user->notify(new SendVerificationCode('123456'))->onQueue('sms');
    
  4. Reusable Notification Logic: Extract common SMS logic into a base notification class:

    abstract class BaseSMSNotification extends Notification
    {
        public function via($notifiable)
        {
            return [KavenegarChannel::class];
        }
    }
    

Workflows

  1. Two-Factor Authentication (2FA):

    • Generate a 6-digit code.
    • Dispatch a SendVerificationCode notification to the user’s phone.
    • Validate the code on submission.
  2. Order Confirmations:

    • Trigger a notification after order processing.
    • Include order details (ID, total, status) in the SMS.
  3. Alerts and Reminders:

    • Send urgent alerts (e.g., password reset, account activity).
    • Schedule reminders (e.g., appointment confirmations).

Integration Tips

  1. Model Binding: Ensure your Notifiable model (e.g., User) implements routeNotificationForSms():

    public function routeNotificationForSms()
    {
        return $this->phone_number; // Store this in your DB
    }
    
  2. Testing: Use Laravel’s NotificationFake to test SMS delivery in unit tests:

    $this->fake()->assertSent(
        SendVerificationCode::class,
        function ($notification) {
            return $notification->toSMS($user) === "Your code: 123456";
        }
    );
    
  3. Error Handling: Override the failed() method in your notification to handle delivery failures:

    public function failed($notifiable, $exception)
    {
        Log::error("Failed to send SMS to {$notifiable->phone_number}: " . $exception->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Ensure KAVENEGAR_API_KEY is never committed to version control (add it to .gitignore).
    • Use Laravel’s .env file for sensitive data.
  2. Sender Number Restrictions:

    • Kavenegar may require verification for certain sender numbers. Test with a valid number before production.
  3. Rate Limits:

    • Kavenegar imposes SMS sending limits. Monitor your usage to avoid throttling:
      try {
          $user->notify(new SendVerificationCode('123456'));
      } catch (\Kavenegar\Api\Exception $e) {
          Log::warning("Kavenegar rate limit exceeded: " . $e->getMessage());
      }
      
  4. Deprecated Laravel Version:

    • This package is designed for Laravel 5.3/5.4. For newer versions, consider:
  5. Missing routeNotificationForSms:

    • Forgetting to implement routeNotificationForSms() will cause Undefined method errors. Always verify the method exists in your Notifiable model.

Debugging

  1. Check Logs: Enable Laravel’s debug mode and check storage/logs/laravel.log for Kavenegar API errors.

  2. Verify API Response: Temporarily log the raw API response in the KavenegarChannel class to debug issues:

    // In KavenegarChannel.php
    public function send($notifiable, $message)
    {
        $response = $this->kavenegar->send($message, $notifiable->routeNotificationForSms());
        Log::debug('Kavenegar Response:', ['response' => $response]);
        return $response;
    }
    
  3. Test with a Valid Number: Use a real phone number (not a sandbox) to ensure the API key and sender are correctly configured.

Tips

  1. Environment-Specific Config: Override Kavenegar settings per environment (e.g., use a sandbox API key in testing):

    # .env.testing
    KAVENEGAR_API_KEY=sandbox_key_here
    
  2. Customize SMS Length: Kavenegar supports long SMS (concatenated messages). If your message exceeds 160 characters, the package will handle it automatically.

  3. Extend the Channel: Add custom logic to the KavenegarChannel class (e.g., logging, retries):

    namespace App\Notifications\Channels;
    
    use Kavenegar\LaravelNotification\KavenegarChannel as BaseKavenegarChannel;
    
    class CustomKavenegarChannel extends BaseKavenegarChannel
    {
        public function send($notifiable, $message)
        {
            // Custom logic (e.g., retry logic)
            return parent::send($notifiable, $message);
        }
    }
    

    Then bind it in your service provider:

    $this->app->bind(
        \Kavenegar\LaravelNotification\KavenegarChannel::class,
        App\Notifications\Channels\CustomKavenegarChannel::class
    );
    
  4. Use Laravel Mixins: Dynamically add SMS notification support to existing models:

    // In a service provider
    User::macro('sendSms', function ($message) {
        return $this->notify(new class($message) extends Notification {
            protected $message;
            public function __construct($message) { $this->message = $message; }
            public function via($notifiable) { return [KavenegarChannel::class]; }
            public function toSMS($notifiable) { return $this->message; }
        });
    });
    

    Usage:

    $user->sendSms("Hello from Laravel!");
    
  5. Monitor Delivery Status: Kavenegar provides delivery reports. Extend the package to log these:

    // In CustomKavenegarChannel
    public function send($notifiable, $message)
    {
        $response = $this->kavenegar->send($message, $notifiable->routeNotificationForSms());
        $this->logDeliveryStatus($response, $notifiable);
        return $response;
    }
    
    protected function logDeliveryStatus($response, $notifiable)
    {
        if (isset($response['status']) && $response['status'] === 'success') {
            Log::info("SMS sent to {$notifiable->phone_number}", ['status' => $response]);
        }
    }
    
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