In this example, I'll show you how to use Twilio to send SMS in Laravel. We'll demonstrate how to use the Twilio API to deliver SMS from a Laravel application. I walk you through laravel send sms twilio step by step.
In this post, you'll learn how to send SMS in Laravel using the Twilio API. Twilio sms may be easily integrated into any Laravel 7 or Laravel 8 application.
Step 1: Install Laravel
In this phase, I install a new Laravel package that allows me to send SMS using the Twilio API. So, to install Laravel, do the following commands:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Create Twilio Account
In this step, you'll create a Twilio account to use in your Laravel application to deliver SMS. Create an account at www.twilio.com.
After you've created a Twilio account, you'll need to add the receiver's sms phone number and confirm it. You cannot send SMS without first verifying your phone number.
.env
TWILIO_SID=XXXXXXXXXXXXXXXXX
TWILIO_TOKEN=XXXXXXXXXXXXX
TWILIO_FROM=+XXXXXXXXXXX
Step 3: Install twilio/sdk Package
In this step, I use composer to install the twilio sdk package in order to use the twilio API. So, here's what we'll do:
composer require twilio/sdk
Step 4: Create Route
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TwilioSMSController;
Route::get('sendSMS', [TwilioSMSController::class, 'index']);
Step 5: Create Controller
We'll create TwilioSMSController and implement send sms logic in this phase, so let's add a new route to the web.php file as follows:
<?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 CodeSolutionStuff.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());
}
}
}
I hope you will like the content and it will help you to learn How to Send SMS using Twilio in Laravel
If you like this content, do share.