Hi there, you know that there are many SMS service provider companies. Twilio is one of them. We can send SMS and WhatsApp messages using Twilio sdk in the Laravel application. We can send SMS using Twilio with twilio/sdk with very few steps.

In this tutorial, I will show you laravel twilio send sms using twilio/sdk package. I will show you a demo tutorial so that you can understand how to send sms using Twilio. 

Before using the Twilio service, we need some credentials like TWILIO_SID, TWILIO_AUTH_TOKEN, and TWILIO_PHONE_NUMBER to verify our client request. So now first login to the Twilio account and get those credentials.

laravel-10-twilio-sms-service-integration

Now we need TWILIO_PHONE_NUMBER and for that, just click the Get Phone Number button and you will get a number,

twilio-laravel-sms-gateway-integration

Now let's start the tutorial of laravel twilio send sms. 

Step 1: Download Fresh Laravel

In the first step of how to send sms in laravel using Twilio, download a fresh Laravel application by the following command:

composer create-project laravel/laravel example-app

 

Step 2: Install  Twilio Package

Now time to install the Twilio package and I am going to use twilio/sdk. So run this below command in your terminal.

composer require twilio/sdk

 

Now update the .env by using the following credentials.

.env

TWILIO_PHONE_NUMBER=""
TWILIO_SID=""
TWILIO_AUTH_TOKEN=""

 

Step 3:  Create Route

Now in this, create a route like the one below to complete the laravel twilio send sms application in Laravel 10.

routes/web.php

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('send-sms', [SMSController::class,'sendSMS']);

 

Read also: Why And When To Use Interface In Laravel Application

 

Step 4: Create Twilio Service Class

In this step, we need to create Twilio service class like below:

App\Services\TwilioService.php

<?php

namespace App\Services;

use Twilio\Rest\Client;

class TwilioService
{
    protected $client;

    public function __construct()
    {
        if (!env('TWILIO_SID')) {
            return;
        }
        $this->client = new Client(env('TWILIO_SID'), env('TWILIO_AUTH_TOKEN'));
    }

    public function sendSMS($to, $message)
    {
        return $this->client->messages->create($to, [
            'from' => env('TWILIO_PHONE_NUMBER'),
            'body' => $message,
        ]);
    }
}

 

Now bind this service class in our service provider like:

App\Providers\AppServiceProvider.php

<?php

namespace App\Providers;

use App\Services\TwilioService;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->bind(TwilioService::class, function ($app) {
            return new TwilioService();
        });
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //
    }
}

 

Step 5: Create Controller

Now in this step, we have to create an SMS controller to define this method to create a sending SMS service application in Laravel 10.

php artisan make:controller SMSController

 

Now update the controller like below:

app/Http/Controllers/SMSCountroller.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Helpers\TwilioService;
use App\Http\Requests\SendSmsRequest;
use App\Models\Appointment;
use App\Models\Patient;
use App\Models\Sms;

class SMSController extends Controller
{
    protected $twilioService;

    public function __construct(TwilioService $twilioService)
    {
        $this->twilioService = $twilioService;
    }

    public function sendSMS(SendSmsRequest $request)
    {
        if ($request->sms_type === 'promotion') {
            $smsBody = Sms::query()->first();
            if ($smsBody) {
                $patients = Patient::all();
                foreach ($patients as $key => $patient) {
                    if ($patient->iso2 === 'bd') {
                        $mobile_number = '+' . $patient->dial_code . substr($patient->mobile_number, -10);
                        $response = $this->twilioService->sendSMS($mobile_number, $smsBody->body);
                    }
                }
            }
            return back()->withError('SMS text not found.');
        }

        $appointment = Appointment::where('patient_id', $request->patient_id)
            ->orderBy('id', 'desc')
            ->first();

        $txt = sprintf(
            "Doctor, %s. Hello, %s. Your ID: %s, Appointment ID: %s, Serial: %u and Appointment Date: %s. Thank you for the Appointment",
            $appointment->doctor->full_name,
            $appointment->patient->full_name,
            $appointment->patient->patient_id_number,
            $appointment->appointment_id_no,
            $appointment->serial_number,
            $appointment->date
        );

        $mobile_number = '+' . $appointment->patient->dial_code . $appointment->patient->mobile_number;
        $response = $this->twilioService->sendSMS($mobile_number, $txt);

        if ($response->sid) {
            return back()->withMessage('SMS sent successfully');
        }
        return back()->withError('Failed to send SMS');
    }
}

 

Now all are set to go. Now run php artisan serve command to start the development server and visit the following URL to check this twilio sms integration in laravel.

URL
http://localhost:8000/send-sms

 

Read also: What Is Service Container And When To Use It In Laravel

 

Conclusion

I have tried my best to show you this laravel twilio send sms. Now we know how to use twilio sdk in php laravel application and using it how to send sms using twilio in laravel application. Hope this twilio sms integration in laravel tutorial will help you.

Category : #laravel

Tags : #laravel