In laravel 11, Twilio provides PHP SDK with some methods that helps developers to send SMS to users mobile phones.
Let’s start to make send sms application using twilio:
Step 1 – Create Account in Twilio
Open browser and type url “www.twilio.com“, and create a account in twilio.
Step 2 – Install Twilio PHP SDK
Run the following command to install php twilio sdk:
composer require twilio/sdk
Edit .env file and add twilio secret key and id in it:
TWILIO_SID=XXXXXXXXXXXXXXXXX
TWILIO_TOKEN=XXXXXXXXXXXXX
TWILIO_FROM=+XXXXXXXXXXX
Step 3 – Create Controller
Run the following command to create controller that handle send sms process:
php artisan make:controller TwilioSMSController
Step 4 – Define Send SMS Method
Edit app/Http/Controllers/TwilioSMSController.php
file, and define methods in it for send sms using twilio:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Exception;
use Twilio\Rest\Client;
class TwilioSMSController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$receiverNumber = "RECEIVER_NUMBER";
$message = "This is testing from itcodstuff.com";
try {
$account_sid = getenv("TWILIO_SID");
$auth_token = getenv("TWILIO_TOKEN");
$twilio_number = getenv("TWILIO_FROM");
$client = new Client($account_sid, $auth_token);
$client->messages->create($receiverNumber, [
'from' => $twilio_number,
'body' => $message]);
dd('SMS Sent Successfully.');
} catch (Exception $e) {
dd("Error: ". $e->getMessage());
}
}
}
Step 5 – Define Routes
Edit routes/web.php
file, and define routes in it to handle send sms requests on controller:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TwilioSMSController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('sendSMS', [TwilioSMSController::class, 'index']);
Step 6 – Test This Application
Run the following command to start application server:
php artisan serve
Type the http://localhost:8000/sendSMS
url on browser to send sms.