In this example, I will show you send SMS using Twilio in laravel. step by step explains laravel – Twilio SMS notifications. This post will give you a simple example of laravel SMS notification twilio. you’ll learn laravel send sms to mobile with Twilio.
In this example, I will give you a very simple example of sending SMS using Twilio API in laravel app. you can easily use this code in laravel 6, laravel 7, laravel 8, and Laravel 9 apps.
If you don’t have an account on Twilio then please create an account in Twilio first
let’s follow the below steps:
Step 1: Install Laravel
first of all, we need to get a fresh Laravel version application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel twiliosender
Step 2: Create Twilio Account
First, you need to create and add a phone number. then you can easily get account SID, Token, and Number.
Create an Account from here: www.twilio.com.
Next, add Twilio Phone Number
Next, you can get account SID, Token, and Number and add on .env file as like bellow:
.env
TWILIO_SID=XXXXXXXXXXXXXXXXX TWILIO_TOKEN=XXXXXXXXXXXXX TWILIO_FROM=+XXXXXXXXXXX
Step 3: Install Twilio/SDK Package
In this step, we need to install Twilio/SDK composer package to use Twilio API. so let’s run the below command:
composer require twilio/sdk
Step 4: Create Route
now we will create one route for calling our example, so let’s add a new route to the web.php file as below:
routes/web.php
<?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 5: Create Controller
in this step, we will create TwilioSMSController and write send SMS logic, so let’s add a new route to the web.php file as below:
app/Http/Controllers/TwilioSMSController.php
<?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 ItSolutionStuff.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()); } } }