In this example, I explain how to send SMS using Twilio in Laravel. We will show how Twilio API to sends SMS in the laravel application. I explain step by step laravel sends SMS Twilio.

In this post, you will learn the easy way to send SMS using Twilio API in laravel. You can easily ingrate Twilio SMS your laravel 7, laravel 8 application.


Step 1: Install Laravel

In this step, I install laravel fresh package for send sms using twilio api. So let’s following commands to install laravel:

composer create-project --prefer-dist laravel/laravel blog


Step 2: Create Twilio Account

I this step you will create twilio account for send sms in laravel application. Create Account from here: www.twilio.com.


After create twilio account you will add receiver sms phone number and verify. Without verify phone number you can not send sms.

.env 

TWILIO_SID=XXXXXXXXXXXXXXXXX
TWILIO_TOKEN=XXXXXXXXXXXXX
TWILIO_FROM=+XXXXXXXXXXX


Step 3: Install twilio/sdk Package

In this step, I install twilio sdk package using composer for use twilio api. So let’s followinf command:

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

In this step, we will create TwilioSMSController and write send sms logic, so let’s add new route to web.php file as bellow:

<?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());
        }
    }
}

I hope you understand how to send sms using twilio api in laravel and it can help you..