Twilio is a powerful API for sending SMS and making voice calls. In this tutorial, we will learn how to integrate **Twilio in Laravel** to send SMS messages.
Step 1: Install Laravel
If you don’t have Laravel installed, run the following command:
composer create-project --prefer-dist laravel/laravel TwilioProject
Step 2: Install Twilio SDK
Run this command to install the Twilio SDK in Laravel:
composer require twilio/sdk
Step 3: Get Twilio API Credentials
Go to the Twilio Console and get your **Account SID**, **Auth Token**, and **Twilio Phone Number**.
Step 4: Configure Twilio in Laravel
Open the `.env` file and add the Twilio credentials:
TWILIO_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=your_twilio_number
Step 5: Create Twilio Service Class
php artisan make:service TwilioService
Now, open app/Services/TwilioService.php and add:
namespace App\Services;
use Twilio\Rest\Client;
class TwilioService {
protected $twilioClient;
protected $from;
public function __construct() {
$this->twilioClient = new Client(env('TWILIO_SID'), env('TWILIO_AUTH_TOKEN'));
$this->from = env('TWILIO_PHONE_NUMBER');
}
public function sendSms($to, $message) {
return $this->twilioClient->messages->create($to, ['from' => $this->from, 'body' => $message]);
}
}
Step 6: Create a Controller
php artisan make:controller TwilioController
Modify app/Http/Controllers/TwilioController.php:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Services\TwilioService;
class TwilioController extends Controller {
protected $twilioService;
public function __construct(TwilioService $twilioService) {
$this->twilioService = $twilioService;
}
public function sendSms(Request $request) {
$request->validate(['phone' => 'required', 'message' => 'required']);
$this->twilioService->sendSms($request->phone, $request->message);
return response()->json(['success' => 'SMS sent successfully!']);
}
}
Step 7: Define Routes
use App\Http\Controllers\TwilioController;
Route::post('/send-sms', [TwilioController::class, 'sendSms']);
Step 8: Test Sending SMS
Test using Postman or CURL:
curl -X POST http://127.0.0.1:8000/send-sms \
-H "Content-Type: application/json" \
-d '{"phone":"+1234567890", "message":"Hello from Laravel Twilio!"}'
Step 9: Deploy and Use in Production
Ensure your Twilio account is verified and deploy your Laravel app.
Conclusion
You have successfully integrated **Twilio SMS API in Laravel**. Now, you can send SMS using Laravel and Twilio easily!

0 Comments