Twillio Integration - Send SMS in Laravel

version : Laravel 10
Post Time : 20-06-2024

twillio integration - Send SMS in Laravel

install laravel
         - composer create-project --prefer-dist laravel/laravel:^10.0 laravel_demo

Follow below commands :- 

                                      
                                        

cd laravel_demo
composer require twilio/sdk
php artisan make:provider TwilioServiceProvider

Configure Twillio Access in .env file


TWILIO_SID=your_twilio_sid
TWILIO_TOKEN=your_twilio_auth_token
TWILIO_FROM=your_twilio_phone_numbe 


app/Providers/TwilioServiceProvider.php

                                      
                                        

<?php

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Library\Services\TwillioServiceSMS;

class TwilioServiceProvider extends ServiceProvider
{
   /**
    * Register services.
    */
   public function register(): void
   {
       //
       $this->app->singleton(TwillioServiceSMS::class, function ($app) {
           return new TwillioServiceSMS();
         });
   }

   /**
    * Bootstrap services.
    */
   public function boot(): void
   {
       //
   }
}

Register TwilioServiceProvider in config/app.php

                                      
                                        

'providers' => [

   // Other Service Providers
    ...
    ...

  App\Providers\TwilioServiceProvider::class,
],

Create app/Library/Services/TwillioServiceSMS.php

                                      
                                        

<?php
namespace App\Library\Services;
use Twilio\Rest\Client;
use Twilio\Exceptions\RestException;
 
class TwillioServiceSMS
{
   protected $twilioClient;

   public function __construct()
   {
       $accountSid = env('TWILIO_SID');
       $authToken = env('TWILIO_TOKEN');
       $this->twilioClient = new Client($accountSid, $authToken);
   }

   public function sendSMS($to, $message)
   {
       $flag = "fail";
       $to ="+91".$to;
       try
        {
           $res = $this->twilioClient->messages->create(
               $to,
               [
                   'from' => env('TWILIO_SMS_FROM'),
                   'body' => $message,
               ]
           );
           if($res->sid){
                $flag = "success";
           }
       }catch(RestException $e){
           $flag =  $e->getMessage(); //die;
       }
       return $flag;
   }
}

Create TwillioDemoController Controller  :
          - php artisan make:controller TwillioDemoController
app/Http/Controllers/TwillioDemoController.php

                                      
                                        

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Library\Services\TwillioServiceSMS;

class TwillioDemoController extends Controller
{
   protected $twilioService;

   public function __construct(TwillioServiceSMS $twilioService)
   {
       $this->twilioService = $twilioService;
   }
   public function SendSMSDemo(Request $request)
   {
       return view('sms_demo');
   }
   public function sendSMS(Request $request)
   {
       $validatedData = $request->validate([
           'phone_no' => 'required|digits:10',
       ]);
       $phone_no = $request->input('phone_no');
       $message_sent =  $this->twilioService->sendSMS($phone_no, "Twillio SMS Demo Testing..");
       if($message_sent == "success")
       {
           $res = "success";
           $msg = "Successfully Sent SMS...!!";
       }else{
           $res = "error";
           $msg = "Something went wrong..!! Please provide valid number..!!";
       }
       return redirect()->route('SendSMSDemo')->with($res , $msg);
   }
}

Create sms_demo blade file :-
Resources/views/sms_demo.blade.php
 

                                      
                                        

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
       <!-- Bootstrap CSS -->
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
   <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>  -->
   <style>
       .error{
           color:red;
       }
       .basic-form{
           display:flex;
           justify-content:center;
       }
   </style>
</head>
<body>
   <div class="mb-3 row text-center">
       <h1>USER INFO</h1>
   </div>
   <div class="row basic-form">
       <div class="col-md-6">
           <form class="dz-form pb-3" action="{{ route('sendSMS') }}" method="POST" name="login_form" id="login_form">
               @csrf
               @if(Session::has('error'))
                   <div class="alert alert-danger" id="success-alert">
                       {{Session::get('error')}}
                   </div>
               @endif
               @if(Session::has('success'))
                   <div class="alert alert-success" id="success-alert">
                       {{Session::get('success')}}
                   </div>
               @endif
               <h3 class="form-title m-t0">SMS DEMO</h3>
               <div class="dz-separator-outer m-b5">
                   <div class="dz-separator bg-primary style-liner"></div>
               </div>
               <div class="form-group mb-3">
                   <input type="text" class="form-control" placeholder="Phone No" name="phone_no" id="phone_no" value="">
                   @error('phone_no')
                       <label class="error">{{ $message }}</label>
                   @enderror
               </div>
               <div class="form-group text-center mb-5 forget-main">
                   <button type="submit" class="btn btn-primary">Save</button>
               </div>
           </form>
       </div>
   </div>
</body>
</html>

routes/web.php

                                      
                                        

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TwillioDemoController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
   return view('welcome');
});

Route::get('/send-sms-demo', [TwillioDemoController::class, 'SendSMSDemo'])->name('SendSMSDemo');
Route::post('/send-sms', [TwillioDemoController::class, 'sendSMS'])->name('sendSMS');