Introduction: Elevating Laravel Applications with SMS Notifications
Laravel is widely considered one of the most elegant, powerful, and developer-friendly PHP frameworks available. Its expressive syntax, comprehensive ecosystem, and built-in features—such as queues, database ORMs (Eloquent), and the unified Notification system—allow developers to build enterprise-grade web applications rapidly. When developing applications in Laravel, implementing direct user notifications is a common requirement. While email notifications are standard, SMS notifications are critical for time-sensitive alerts like security verification codes (OTPs), invoice receipts, and dispatch updates.
Rather than using messy, unstructured PHP scripts, integrating a SMS API Laravel Integration should follow the framework's architectural patterns. By leveraging Laravel's native HTTP client facade, creating a custom Notification Channel, and queueing SMS jobs, developers can build a robust, scalable communication pipeline. This comprehensive guide walks through these methods step-by-step.
Prerequisites: Getting Started
Before coding, ensure you have gathered the following integration requirements:
- Laravel Environment: An active Laravel project (version 8.x, 9.x, 10.x, or 11.x).
- Credentials: Sign up for an account on BlackSMS and get your secure API Key and Sender ID (Header) from the settings console.
- DLT Details (India): If sending SMS messages to Indian users, obtain your 19-digit Principal Entity ID (PE ID) and template IDs.
Method 1: Basic Integration using Laravel Http Facade
For quick implementations, such as checking connection settings or firing one-off alerts, you can use Laravel's native HTTP client wrapper (the Http facade). It is clean, readable, and handles JSON payloads automatically.
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
public function sendDirectSMS(string $phone, string $message, string $templateId)
{
$response = Http::acceptJson()->post('https://api.blacksms.in/v1/send', [
'api_key' => config('services.blacksms.key'),
'sender_id' => config('services.blacksms.sender'),
'phone' => $phone,
'message' => $message,
'pe_id' => config('services.blacksms.pe_id'),
'template_id' => $templateId,
]);
if ($response->successful() && $response->json('status') === 'success') {
Log::info("BlackSMS sent successfully to {$phone}. ID: " . $response->json('message_id'));
return true;
}
Log::error("BlackSMS failed to deliver. Response: " . $response->body());
return false;
}
Ensure you add the configurations to your config/services.php file:
'blacksms' => [
'key' => env('BLACKSMS_API_KEY'),
'sender' => env('BLACKSMS_SENDER_ID', 'BLKSMS'),
'pe_id' => env('BLACKSMS_PE_ID'),
],
Method 2: Building a Custom Laravel Notification Channel
To use Laravel's native notification ecosystem (e.g., $user->notify(new OrderShipped($order))), you should build a custom SMS channel driver. This decouples the delivery details from the notification template, allowing you to switch providers or send messages across multiple channels (SMS, mail, database) simultaneously.
Step 1: Create the Custom Channel Class
Create a class named BlackSmsChannel under a new directory app/Notifications/Channels:
<?php
namespace App\Notifications\Channels;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class BlackSmsChannel
{
public function send($notifiable, Notification $notification)
{
// 1. Get destination phone number from the model
if (!$to = $notifiable->routeNotificationFor('sms')) {
return;
}
// 2. Fetch formatted message details from notification class
$messageData = $notification->toBlackSms($notifiable);
$response = Http::acceptJson()->post('https://api.blacksms.in/v1/send', [
'api_key' => config('services.blacksms.key'),
'sender_id' => config('services.blacksms.sender'),
'phone' => $to,
'message' => $messageData['content'],
'pe_id' => config('services.blacksms.pe_id'),
'template_id' => $messageData['template_id'],
]);
if ($response->failed() || $response->json('status') !== 'success') {
Log::error("BlackSMS Channel Delivery Failure to {$to}. Error: " . $response->body());
}
}
}
Step 2: Create your Notification Template
Create a notification class using the Artisan command: php artisan make:notification OrderShippedNotification. Update the file to utilize your new channel driver:
<?php
namespace App\Notifications;
use App\Notifications\Channels\BlackSmsChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
class OrderShippedNotification extends Notification implements ShouldQueue
{
use Queueable;
protected $orderId;
protected $deliveryDate;
public function __construct($orderId, $deliveryDate)
{
$this->orderId = $orderId;
$this->deliveryDate = $deliveryDate;
}
// Register the custom channel
public function via($notifiable)
{
return [BlackSmsChannel::class];
}
// Format the payload and define DLT parameters
public function toBlackSms($notifiable)
{
return [
'content' => "Dear Customer, your order {$this->orderId} has been shipped and will deliver by {$this->deliveryDate}.",
'template_id' => '1207161712345678901' // Approved DLT Template ID
];
}
}
Step 3: Define Routing on your User Model
Add a routeNotificationForSms method to your Notifiable model (e.g., the User model) to define where the framework should look for the phone number:
class User extends Authenticatable
{
use Notifiable;
public function routeNotificationForSms($notification)
{
// Clean and return the phone number field
return preg_replace('/[^0-9]/', '', $this->phone_number);
}
}
The Importance of Queueing SMS Notifications
Sending an HTTP request to an external API during a web request adds network latency to the user's connection. If the gateway takes 2 seconds to respond, your page load slows down. To keep your application fast, always queue your notifications by implementing the ShouldQueue interface on your notification class. This offloads the SMS request to your background queue workers (powered by database, Redis, or SQS queues), ensuring near-instant page response times for the user.
Conclusion: Production Laravel Architectures
Integrating SMS alerts into Laravel is straightforward and clean when using the framework's native tools. By wrapping the API within a custom Notification Channel driver and utilizing queues, you can manage critical notifications without impacting your application's speed or code organization. BlackSMS provides low-latency REST APIs designed to support Laravel integrations, with comprehensive DLT compliance tools. Set up your integration today and optimize your framework communications.