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.
Installation:
composer require kavenegar/laravel-notification
Register the service provider in config/app.php:
Kavenegar\LaravelNotification\KavenegarServiceProvider::class
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'),
],
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'));
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!";
}
Multi-Channel Notifications: Combine Kavenegar with other channels (e.g., Mail) for hybrid notifications:
public function via($notifiable)
{
return [MailChannel::class, KavenegarChannel::class];
}
Queueing Notifications: Leverage Laravel’s queue system to send SMS asynchronously:
$user->notify(new SendVerificationCode('123456'))->onQueue('sms');
Reusable Notification Logic: Extract common SMS logic into a base notification class:
abstract class BaseSMSNotification extends Notification
{
public function via($notifiable)
{
return [KavenegarChannel::class];
}
}
Two-Factor Authentication (2FA):
SendVerificationCode notification to the user’s phone.Order Confirmations:
Alerts and Reminders:
Model Binding:
Ensure your Notifiable model (e.g., User) implements routeNotificationForSms():
public function routeNotificationForSms()
{
return $this->phone_number; // Store this in your DB
}
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";
}
);
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());
}
API Key Exposure:
KAVENEGAR_API_KEY is never committed to version control (add it to .gitignore)..env file for sensitive data.Sender Number Restrictions:
Rate Limits:
try {
$user->notify(new SendVerificationCode('123456'));
} catch (\Kavenegar\Api\Exception $e) {
Log::warning("Kavenegar rate limit exceeded: " . $e->getMessage());
}
Deprecated Laravel Version:
notifications-channels/sms.Missing routeNotificationForSms:
routeNotificationForSms() will cause Undefined method errors. Always verify the method exists in your Notifiable model.Check Logs:
Enable Laravel’s debug mode and check storage/logs/laravel.log for Kavenegar API errors.
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;
}
Test with a Valid Number: Use a real phone number (not a sandbox) to ensure the API key and sender are correctly configured.
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
Customize SMS Length: Kavenegar supports long SMS (concatenated messages). If your message exceeds 160 characters, the package will handle it automatically.
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
);
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!");
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]);
}
}
How can I help you explore Laravel packages today?