Laravel 11 Send SMS using Twilio Tutorial

In this Laravel 11 Send SMS using Twilio Tutorial guide, we will explore how to send SMS messages within a Laravel application using the Twilio API. Twilio is a cloud-based communication platform that offers a straightforward and robust API for sending SMS messages, making it a great option for incorporating SMS features into your Laravel projects. We will detail the entire process, from setting up a Twilio account to integrating the code into your Laravel project.

Step 1 – Set Up a Twilio Account

Navigate to “www.twilio.com” in your browser and register for a Twilio account.

Step 2 – Install the Twilio PHP SDK

Execute this command to install the Twilio PHP SDK:

composer require twilio/sdk

Then, update your .env file with your Twilio credentials:

TWILIO_SID=XXXXXXXXXXXXXXXXX
TWILIO_TOKEN=XXXXXXXXXXXXX
TWILIO_FROM=+XXXXXXXXXXX

Step 3 – Create a Controller

Generate a new controller to manage the SMS sending process:

php artisan make:controller TwilioSMSController

Step 4 – Implement the SMS Sending Method

Open the app/Http/Controllers/TwilioSMSController.php file and add the following method to send an SMS using Twilio:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Exception;
use Twilio\Rest\Client;

class TwilioSMSController extends Controller
{
/**
* Handle the SMS sending process.
*
* @return \Illuminate\Http\Response
*/
public function sendSMS()
{
$toNumber = "RECEIVER_NUMBER";
$messageContent = "This is a test message from itcodstuff.com";

try {
$sid = getenv("TWILIO_SID");
$token = getenv("TWILIO_TOKEN");
$fromNumber = getenv("TWILIO_FROM");

$twilioClient = new Client($sid, $token);
$twilioClient->messages->create($toNumber, [
'from' => $fromNumber,
'body' => $messageContent
]);

return response()->json(['message' => 'SMS Sent Successfully.']);

} catch (Exception $e) {
return response()->json(['error' => 'Error: '. $e->getMessage()], 500);
}
}
}

Step 5 – Configure Routes

Edit the routes/web.php file to set up a route for sending SMS through the controller:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TwilioSMSController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here you can define routes for your application. These routes are
| loaded by the RouteServiceProvider within a group containing the
| "web" middleware group.
|
*/

Route::get('sendSMS', [TwilioSMSController::class, 'sendSMS']);

Step 6 – Run and Test Your Application

Start the Laravel server with the following command:

php artisan serve

Then, visit http://localhost:8000/sendSMS in your web browser to test the SMS sending functionality.