Implement SMS in Laravel Using MSG91 – A Complete Guide

by Akshat V. 4 minute read 25 views

MSG91 Flow API integration in Laravel boosts real-time SMS delivery for web and mobile apps, enabling faster OTPs, alerts, and reminders using dynamic templates.

Key Points

  • Laravel + MSG91 supports template-based SMS with 99% delivery accuracy and global reach.
  • Reduce OTP delivery time by 40% using MSG91’s optimized route system in Laravel apps.
  • Enhance user trust with 2x faster appointment and order alerts via MSG91 in web apps.

Introduction

Instant messaging is critical for modern applications, from OTPs and order alerts to appointment confirmations. In this guide, you’ll learn how to integrate the MSG91 Flow API into a full-stack Laravel web app for sending dynamic SMS messages using pre-approved templates—ideal for any Android, iOS app developer, or web backend engineer.

Why Use MSG91 Flow API?

Discover the core benefits of using MSG91 Flow API in Laravel.

MSG91 offers a robust and secure way to deliver SMS messages with high reliability and compliance. Using pre-approved templates with variable support, it simplifies bulk messaging, transactional alerts, and real-time user notifications. It's particularly effective for web app development and mobile applications needing consistent communication.

Set Up MSG91

Create and configure your MSG91 account for SMS delivery.

Start by registering at MSG91, setting up a Flow template with variables like {{var1}}, {{var2}}, and then generating your AuthKey. This allows you to connect your Laravel app with MSG91’s SMS gateway.

Add Environment Variables

Store sensitive credentials securely using Laravel’s .env file.

Add your MSG91 authentication details and route information to .env. This keeps your API keys secure and easily configurable across environments.

                                        MSG91_AUTH_KEY=your_auth_key  
MSG91_ROUTE=your_route  
MSG91_COUNTRY=91
                                    

Explanation of the Msg91Service Class

Understand how the Msg91Service class wraps all SMS functionality in Laravel.

This service class acts as a centralized interface to interact with the MSG91 Flow API. It makes your code modular, clean, and easier to maintain, especially useful for full-stack Laravel web app development.

Class Properties

                                        protected $apiKey;     // Your MSG91 API key from environment variable  
protected $senderId;   // Sender ID (e.g., "PETOVC")  
protected $route;      // Route type (optional, if required)  
protected $country;    // Country code (e.g., "91" for India)  
protected $url;        // MSG91 Flow API endpoint URL
                                    

These are used internally to authenticate and configure your API request to MSG91.

Constructor

Learn how the service class initializes with environment values.

                                        public function __construct()  
{  
    $this->apiKey = env('MSG91_AUTH_KEY');  
    $this->senderId = 'PETOVC';  
    $this->route = env('MSG91_ROUTE');  
    $this->country = env('MSG91_COUNTRY');  
    $this->url = "https://control.msg91.com/api/v5/flow";  
}
                                    

This constructor automatically pulls values from the .env file, ensuring your Laravel app is ready for SMS delivery.

Method: customSendSms

This method is responsible for sending SMS messages using the Flow template system.

public function customSendSms(string $mobile, string $templateId, array $variables): bool

Purpose:

Send an SMS with dynamic data via MSG91 Flow API.

Parameters:

  • $mobile: Phone number without country code

  • $templateId: Flow template ID

  • $variables: Key-value pairs for placeholders like {{var1}}, {{var2}}

Returns:

  • true on success

  • false on failure

How It Works Internally

MSG91 requires a specific payload format for the Flow API. Here's how this function prepares it:

                                        [
    'template_id' => 'template_id_here',
    'recipients' => [
        [
            'mobiles' => '91XXXXXXXXXX',
            'var1' => 'value1',
            'var2' => 'value2'
        ]
    ]
]
                                    

This internal structure matches the variable setup in your Flow template to deliver the message correctly.

Msg91Service.php

Here’s the complete code for the Msg91Service class to use in your Laravel app.

                                        namespace App\Service; 
use GuzzleHttp\Client; 

class Msg91Service 
{ 
    protected $apiKey; 
    protected $senderId; 
    protected $route;
    protected $country; 
    protected $url; 

    public function __construct() 
    { 
        $this->apiKey = env('MSG91_AUTH_KEY'); 
        $this->senderId = 'PETOVC'; 
        $this->route = env('MSG91_ROUTE'); 
        $this->country = env('MSG91_COUNTRY'); 
        $this->url = "https://control.msg91.com/api/v5/flow"; 
    } 

    /** 
    * Send an SMS using MSG91 
    * 
    * @param string $mobile - The recipient's mobile number  
    * @param string $templateId - The template ID for the SMS  
    * @param array $variables - Variables to be replaced in the template  
    * @return bool 
    */ 
    public function customSendSms ($mobile, $templateId, $variables) 
    { 
        $client = new Client(); 
        $data = [ 
            'template_id' => $templateId, 
            'recipients' => [ 
                [ 'mobiles' => '91' . $mobile ] 
            ] 
        ]; 

        foreach ($variables as $key => $value) { 
            $data['recipients'][0][$key] = $value; 
        } 

        $response = $client->post($this->url, [ 
            'json' => $data, 
            'headers' => [ 
                'authkey' => $this->apiKey, 
                'Content-Type' => 'application/json', 
            ], 
        ]); 

        $responseBody = json_decode($response->getBody()->getContents()); 
        return $responseBody->type == 'success'; 
    } 
}
                                    

This class gives you full control over SMS delivery and integrates smoothly into any Laravel-based web app development project.

How to Use It in Your Laravel Project

Here’s an example controller showing how to use the service.

                                        use App\Service\Msg91Service; 

class SmsController extends Controller 
{ 
    protected $msg91; 

    public function __construct(Msg91Service $msg91) 
    { 
        $this->msg91 = $msg91; 
    } 

    public function sendSms() 
    { 
        $mobile = '9876543210'; 
        $templateId = 'your_template_id_from_msg91'; 
        $variables = [ 
            'var1' => 'John', 
            'var2' => 'Appointment at 5 PM' 
        ]; 

        $result = $this->msg91->customSendSms($mobile, $templateId, $variables); 

        if ($result) { 
            return response()->json(['message' => 'SMS sent successfully']); 
        } else { 
            return response()->json(['message' => 'Failed to send SMS'], 500); 
        } 
    } 
}
                                    

This is a real-world example useful for any Android app developer or iOS app developer integrating SMS into a mobile app via Laravel’s backend.

Common Use Cases

Explore where and how you can use this integration.

  • User verification via OTPs

  • Transactional updates like payments or orders

  • Appointment reminders in health apps

  • Shipping notifications in ecommerce platforms

  • Event invites or promotions

These use cases are common in modern web and mobile app development.

Best Practices

Follow these practices for optimal performance and security.

  • Validate phone numbers before sending

  • Keep credentials in .env only

  • Gracefully handle API errors or failures

  • Use Laravel's dependency injection to keep code modular

  • Monitor usage and delivery via the MSG91 dashboard

Final Words

Adding SMS functionality to your full-stack Laravel web app using MSG91 Flow API is easy and powerful. The approach shown keeps your code scalable and secure, allowing you to trigger real-time alerts, OTPs, and updates with just a few lines of code.

Whether you're an Android app developer, iOS app developer, or Laravel engineer, this guide empowers you to add robust SMS features to your projects.

Tech Stack & Version

Frontend

  • JavaScript
  • HTML5
  • CSS3

Backend

  • Laravel 8+
  • MySQL
  • GuzzleHTTP

Deployment

  • DigitalOcean
  • Linode
  • AWS
img

©2025Digittrix Infotech Private Limited , All rights reserved.