Here is a Laravel 10 send SMS using Twilio tutorial example.
Prerequisites
- A Laravel 10 application
- A Twilio account
- A Twilio phone number
Steps
- Install the Twilio PHP SDK.
composer require twilio/sdk
- 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
- 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']);
}
}
- Create a route to call the controller.
Route::post('/send-sms', 'SMSController@sendSMS');
- Test the SMS sending by sending a POST request to the
/send-sms
endpoint with theto
andmessage
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.