laravel-fast2sms maintained by itxshakil
Laravel Fast2sms 📲
A Laravel package for sending SMS using the Fast2sms API with a fluent, expressive interface.
Supports Quick SMS, DLT templates, OTP, queueing, scheduling, and balance checks.
Table of Contents
- Requirements
- Features
- Quick Start Guide
- Installation
- Configuration
- Basic Usage
- API Methods
- Error Handling
- Advanced Features
- Documentation
- Contributing
- License
Requirements
- PHP 8.3 or higher
- Laravel 12 or higher (the package relies on
illuminate/supportv12+)
✨ Features
- Fluent Interface: Chainable API for building and sending SMS.
- Multiple Routes: Supports Quick SMS, DLT SMS, and OTP SMS.
- Queue Support: Built-in job queueing for asynchronous processing.
- Easy Configuration: Simple config file and environment variable setup.
- DLT Compliant: Send DLT messages with templates and variables.
- Service & Facade: Use the
Fast2smsservice directly or via facade. - API Helpers: Check wallet balance and DLT details.
- Artisan Commands: Publish configuration and monitor balance.
🚀 Quick Start Guide
- ✅ Laravel Notification Channel Support
- ✅ Fluent API (Fast2sms::to()->message()->send())
- ✅ Database Logging (Optional tracking of all sent SMS)
- ✅ Log Driver (Zero-cost local development)
- ✅ DLT Support (Sender ID, Template ID)
- ✅ OTP Support
- ✅ Balance Monitoring (CLI & Events)
- ✅ Queuing & Faking Support
- ✅ Validation Helpers (Indian phone number validation)
- ✅ Automatic Retries (Built-in resilience)
⚡ Quick Start
-
Install via Composer:
composer require itxshakil/laravel-fast2sms -
Publish Configuration:
php artisan vendor:publish --tag=fast2sms-config -
Database Logging (Optional):
php artisan vendor:publish --tag="fast2sms-migrations" php artisan migrate -
Update Environment Variables: Add to your
.env:FAST2SMS_API_KEY="YOUR_API_KEY" FAST2SMS_DEFAULT_SENDER_ID="FSTSMS" FAST2SMS_DEFAULT_ROUTE="dlt" FAST2SMS_DRIVER="api" # Use 'log' for local development FAST2SMS_DATABASE_LOGGING=true -
Send Your First DLT SMS:
use Shakil\Fast2sms\Facades\Fast2sms; Fast2sms::dlt( numbers: '9999999999', templateId: 'YOUR_TEMPLATE_ID', variablesValues: ['John Doe'], senderId: 'YOUR_SENDER_ID' );
⚙️ Installation
Install the package via Composer:
composer require itxshakil/laravel-fast2sms
Supports Laravel auto-discovery. No manual provider registration required.
🛠️ Configuration
Publish the configuration file:
php artisan vendor:publish --tag=fast2sms-config
Creates fast2sms.php in your config directory.
Environment Variables:
Update your .env file:
FAST2SMS_API_KEY="YOUR_API_KEY"
FAST2SMS_DEFAULT_SENDER_ID="FSTSMS"
FAST2SMS_DEFAULT_ROUTE="dlt"
📝 Basic Usage
Use the Fast2sms facade for convenience. Three primary sending methods, each with a dedicated helper.
Quick SMS
use Shakil\Fast2sms\Facades\Fast2sms;
use Shakil\Fast2sms\Enums\SmsLanguage;
Fast2sms::quick('9999999999', 'Hello, this is a Quick SMS!');
Fast2sms::quick('9999999999', 'नमस्ते! यह एक क्विक एसएमएस है।', SmsLanguage::UNICODE);
DLT SMS
use Shakil\Fast2sms\Facades\Fast2sms;
Fast2sms::dlt(
numbers: '9999999999',
templateId: 'YOUR_TEMPLATE_ID',
variablesValues: ['John Doe'],
senderId: 'YOUR_SENDER_ID'
);
OTP SMS
use Shakil\Fast2sms\Facades\Fast2sms;
Fast2sms::otp('9999999999', '123456');
Fluent Interface
use Shakil\Fast2sms\Facades\Fast2sms;
use Shakil\Fast2sms\Enums\SmsRoute;
Fast2sms::to('9999999999')
->route(SmsRoute::DLT)
->senderId('YOUR_SENDER_ID')
->templateId('YOUR_TEMPLATE_ID')
->variables(['John Doe'])
->send();
Check Wallet Balance
use Shakil\Fast2sms\Facades\Fast2sms;
$response = Fast2sms::checkBalance();
if ($response->success()) {
echo "Wallet Balance: {$response->balance}\n";
echo "SMS Count: {$response->smsCount}\n";
}
Check DLT Manager Details
use Shakil\Fast2sms\Facades\Fast2sms;
use Shakil\Fast2sms\Enums\DltManagerType;
use Shakil\Fast2sms\Responses\DltManagerResponse;
// Get DLT sender IDs
/** @var DltManagerResponse $sendersResponse */
$sendersResponse = Fast2sms::dltManager(DltManagerType::SENDER);
foreach ($sendersResponse->getSenders() as $sender) {
echo "Sender ID: {$sender['sender_id']} | Entity ID: {$sender['entity_id']}\n";
}
📚 API Methods
| Method | Description |
|---|---|
| `->to(string | array $numbers)` |
->message(string $message) |
Sets message content (DLT: template ID). |
->senderId(string $senderId) |
Sets DLT-approved sender ID. |
->route(SmsRoute $route) |
Sets SMS route (DLT, QUICK, OTP, etc.). |
->entityId(string $entityId) |
Sets DLT Principal Entity ID. |
->templateId(string $templateId) |
Sets DLT Content Template ID. |
| `->variables(array | string $values)` |
->flash(bool $flash) |
Toggles flash message. |
->language(SmsLanguage $language) |
Sets message language (ENGLISH, UNICODE). |
| `->schedule(string | DateTimeInterface $time)` |
->send() |
Sends SMS with configured parameters. |
->quick(...) |
Quick helper to send simple SMS. |
->dlt(...) |
Helper for DLT messages. |
->otp(...) |
Helper for OTP messages. |
->checkBalance() |
Retrieves wallet balance. |
->dltManager(string $type) |
Retrieves DLT manager details for sender or template. |
⚠️ Exceptions
All errors throw Fast2smsException.
Catch them when handling SMS sending:
use Shakil\Fast2sms\Exceptions\Fast2smsException;
try {
Fast2sms::quick('9999999999', 'Hello World');
} catch (Fast2smsException $e) {
logger()->error("SMS failed: " . $e->getMessage());
}
🧩 Advanced Features
🚀 Queue Integration
Supports Laravel's queue system for asynchronous SMS sending.
Queue Configuration:
// config/queue.php
'connections' => [
'redis' => [
'driver' => 'redis',
// ... other redis configuration
],
],
Queueing SMS Messages:
use Shakil\Fast2sms\Facades\Fast2sms;
// Queue a Quick SMS
Fast2sms::quickQueue('9999999999', 'Hello from queue!');
// Queue a DLT SMS
Fast2sms::dltQueue(
numbers: '9999999999',
templateId: 'YOUR_TEMPLATE_ID',
variablesValues: ['John Doe'],
senderId: 'YOUR_SENDER_ID'
);
// Queue an OTP SMS
Fast2sms::otpQueue('9999999999', '123456');
Advanced Queue Options:
use Shakil\Fast2sms\Facades\Fast2sms;
use Shakil\Fast2sms\Enums\SmsRoute;
Fast2sms::to('9999999999')
->message('Test message')
->route(SmsRoute::QUICK)
->onConnection('redis') // Specify queue connection
->onQueue('sms') // Specify queue name
->delay(now()->addMinutes(10)) // Add delay
->queue(); // Queue the SMS
Queue Methods:
| Method | Description |
|---|---|
->queue() |
Queue SMS using default settings |
->onConnection(string $name) |
Set queue connection |
->onQueue(string $queue) |
Set queue name |
->delay($delay) |
Set delay before processing |
->quickQueue() |
Queue Quick SMS |
->dltQueue() |
Queue DLT SMS |
->otpQueue() |
Queue OTP SMS |
Validation Helpers
The package includes a custom validation rule to ensure phone numbers are valid 10-digit Indian mobile numbers.
use Shakil\Fast2sms\Rules\Fast2smsPhone;
$request->validate([
'phone' => ['required', new Fast2smsPhone],
]);
📱 Notifications Channel
Use Fast2sms as a notification channel in your Laravel applications. The SmsChannel supports both simple strings and fluent SmsMessage objects.
Create a Notification:
use Illuminate\Notifications\Notification;
use Shakil\Fast2sms\Notifications\Messages\SmsMessage;
use Shakil\Fast2sms\Enums\SmsRoute;
class OrderShipped extends Notification
{
public function via($notifiable)
{
return ['fast2sms'];
}
public function toSms($notifiable)
{
// Option 1: Return a simple string (uses default route/sender)
// return "Your order #123 has been shipped!";
// Option 2: Return a fluent SmsMessage object
return (new SmsMessage)
->to($notifiable->phone) // Optional: will fallback to routeNotificationForSms
->route(SmsRoute::DLT)
->template('TEMPLATE_ID', ['Order #123'])
->from('SENDER');
}
}
Model Setup:
Ensure your model has a routeNotificationForSms method or a phone attribute:
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use Notifiable;
public function routeNotificationForSms()
{
return $this->phone;
}
}
Direct Sending from Notification Message:
The SmsMessage can also be sent directly if needed:
(new SmsMessage("Hello"))->to('9999999999')->send();
📊 Database Logging (Optional)
Schedule the command:
php artisan sms:monitor --threshold=500
If no threshold is specified, the value from your configuration file will be used:
// config/fast2sms.php
'balance_threshold' => 1000,
Listen for the event in AppServiceProvider:
use App\Notifications\LowSmsBalanceNotification;
use Illuminate\Support\Facades/Event;
use Illuminate\Support\Facades\Notification;
use Shakil\Fast2sms\Events\LowBalanceDetected;
public function boot(): void
{
Event::listen(function (LowBalanceDetected $event) {
Notification::route('mail', 'dev@example.com')
->notify(new LowSmsBalanceNotification(
$event->balance,
$event->threshold
));
});
}
Example schedule in App\Console\Kernel:
protected function schedule(Schedule $schedule)
{
$schedule->command('sms:monitor')->hourly();
}
📚 Documentation
Learn how to use Laravel Fast2sms effectively:
Getting Started
Features
🤝 Contributing
Contributions are always welcome!
Open an issue or submit a pull request for bugs or suggestions.
📄 License
This package is open-source software licensed under the MIT license.