How To Send SMS Using Twilio In Your Laravel 10 Application

How To Send SMS Using Twilio In Your Laravel 10 Application

Here is a Laravel 10 send SMS using Twilio tutorial example.

Prerequisites

  • A Laravel 10 application
  • A Twilio account
  • A Twilio phone number

Steps

  1. Install the Twilio PHP SDK.
composer require twilio/sdk
  1. Set up your Twilio credentials in the .env file.
TWILIO_ACCOUNT_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=your_phone_number
  1. Create a controller to send the SMS.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Twilio\Rest\Client;

class SMSController extends Controller
{
    public function sendSMS(Request $request)
    {
        $client = new Client();

        $to = $request->input('to');
        $message = $request->input('message');

        $client->messages->create(
            $to,
            [
                'from' => env('TWILIO_PHONE_NUMBER'),
                'body' => $message,
            ]
        );

        return response()->json(['message' => 'SMS sent successfully']);
    }
}
  1. Create a route to call the controller.
Route::post('/send-sms', 'SMSController@sendSMS');
  1. Test the SMS sending by sending a POST request to the /send-sms endpoint with the to and message parameters.

For example, the following request will send an SMS to the number 1234567890 with the message This is an SMS from Laravel!:

curl -X POST http://localhost:8000/send-sms -d 'to=1234567890&message=This is an SMS from Laravel!'

I hope this tutorial helps you send SMS using Twilio in your Laravel 10 application.

Leave a Reply