Laravel 12 - How to Send SMS Using Twilio.
Laravel 12 - How to Send SMS Using Twilio.
In this tutorial we will learn how to integrate Twilio to send SMS in Laravel 12, allowing your application to send messages seamlessly, reach users instantly, and enhance communication directly from your app.
Quick Overview
This guide walks you through integrating Twilio SMS functionality into a Laravel 12 project. It covers setting up a new Laravel application, installing the Twilio SDK, and creating a controller to handle sending SMS messages. Routes are defined to connect the frontend form with the backend logic, and a Blade view is provided for users to enter a phone number and message. The guide also shows how to retrieve Twilio credentials and store them securely in the .env file. Finally, the Laravel development server is started, and the setup is tested by sending an SMS through the web interface, confirming that your Laravel 12 application is ready to send messages via Twilio.
Step # 1 : Initialize a Fresh Laravel Project or Continue with an Existing One.
To get started, you’ll need a Laravel 12 application. You can either start fresh with a new project or continue working inside an existing one. If you have the Laravel Installer installed globally, you can create a new project named message using this command.
laravel new message
If the Laravel Installer isn’t installed, no problem you can also create the project using Composer.
composer create-project laravel/laravel --prefer-dist message
Using Composer skips the interactive setup and scaffolds a clean Laravel application. On the other hand, if you use the Laravel Installer, you’ll go through a short setup wizard. Here’s a suggested configuration.
- Starter Kit: Select None for a minimal, framework only installation.
- Testing Framework: Choose Pest for a clean and simple testing setup.
- Database: Pick MySQL as your primary database engine.
- Run Migration: Type Yes to run the default migrations immediately.
- Frontend Dependencies: Choose Yes so Laravel installs all the required frontend packages automatically.
Once the installation is complete, Laravel will create a directory named message, install all the necessary files and dependencies, and run the default migrations. At this point, your Laravel 12 application is ready for you to start building features or customizing it as needed.
Step # 2 : Move into Your Laravel Project Directory.
Now that your Laravel project is ready, open your favorite terminal Git Bash, Command Prompt, or any terminal you prefer and navigate to your project folder. For example, if your project is located at c:\xampp\htdocs\message, use the following command.
cd c:xampp/htdocs/message
This ensures that your terminal is inside the project, so any commands you run like starting the development server, installing packages, or updating files will affect the correct Laravel application.
Step # 3 : Install the Twilio Package.
Next, we need to bring Twilio’s SDK into our Laravel project. Run the following command.
composer require twilio/sdk
This package makes it easy for Laravel to work with Twilio’s messaging services. With it, you’ll be able to send SMS, make calls, and handle other communication tasks efficiently. The SDK simplifies interaction with Twilio’s API, helping you deliver messages seamlessly without having to deal with low-level API requests.
Step # 4 : Create a Message Controller.
Now it’s time to create a controller that will handle sending SMS messages through Twilio. In your terminal, run the following command to generate a new controller named MessageController.
php artisan make:controller MessageController
Once the controller is created, update it with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twilio\Rest\Client;
use Exception;
class MessageController extends Controller
{
public function index()
{
// Display the view containing the form.
return view('message');
}
function store(Request $request)
{
// Retrieve Twilio credentials from the .env file
$twilioSid = env('TWILIO_SID');
$twilioAuthToken = env('TWILIO_AUTH_TOKEN');
$twilioNumber = env('TWILIO_NUMBER');
// Extract the phone number and message from the request
// Make sure the phone number is in the international format, e.g., +923XXXXXXXXX for Pakistan
$to = $request->phone;
$messageBody = $request->message;
try {
// Create a new Twilio client using the retrieved credentials
$client = new Client($twilioSid, $twilioAuthToken);
// Send the SMS message to the specified phone number
$client->messages->create($to, [
'from' => $twilioNumber, // Twilio phone number
'body' => $messageBody // The message text
]);
// Return success message if the message is sent successfully
return "Message sent successfully!";
} catch (Exception $e) {
// Handle any errors that occur during message sending and return an error message
return "Error sending message: " . $e->getMessage();
}
}
}
This controller handles both displaying the form and sending messages. The index method is responsible for showing the form where users can enter the recipient’s phone number and the message, while the store method takes care of sending the SMS using the Twilio credentials stored securely in your .env file. This setup keeps your code organized and ensures that sensitive information, like your Twilio keys, remains protected and separate from your application logic.
Step # 5 : Set Up Routes.
Next, we need to set up the routes that connect the frontend form to our controller. To do this, import the MessageController at the top of your web.php file and then define the routes that will display the form and handle form submissions.
use App\Http\Controllers\MessageController;
Route::get('/', [MessageController::class, 'index']);
Route::post('/message', [MessageController::class, 'store']);
The first route displays the message form by calling the index method, while the second route handles form submissions and triggers the store method to send the SMS via Twilio. By setting up these routes, you ensure smooth communication between your frontend and backend, allowing users to send messages quickly and efficiently.
Step # 6 : Create a View.
Create a Blade file named message.blade.php and add the following HTML to provide a form where users can enter a phone number and a message to send via Twilio.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Shotcut - Twilio SMS</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-gray-100 min-h-screen flex items-center justify-center">
<div class="w-full max-w-md p-6 bg-gray-800 rounded-2xl shadow-lg">
<h4 class="text-xl md:text-xl font-bold text-center mb-6">Code Shotcut - Send SMS via Twilio</h4>
@if ($message = Session::get('success'))
<div class="mb-4 p-3 rounded bg-green-600 text-white">
{{ $message }}
</div>
@endif
@if ($message = Session::get('error'))
<div class="mb-4 p-3 rounded bg-red-600 text-white">
{{ $message }}
</div>
@endif
<form method="POST" action="{{ url('/message') }}" class="space-y-4">
@csrf
<div>
<label for="phone" class="block mb-1 font-medium">Phone Number</label>
<input type="text" name="phone" id="phone" placeholder="+923XXXXXXXXX"
class="w-full p-3 rounded bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 @error('phone') border-red-500 @enderror">
@error('phone')
<p class="text-red-500 text-sm mt-1">{{ $message }}</p>
@enderror
</div>
<div>
<label for="message" class="block mb-1 font-medium">Message</label>
<textarea name="message" id="message" rows="4" placeholder="Enter your message..."
class="w-full p-3 rounded bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 @error('message') border-red-500 @enderror"></textarea>
@error('message')
<p class="text-red-500 text-sm mt-1">{{ $message }}</p>
@enderror
</div>
<div>
<button type="submit"
class="w-full bg-blue-600 hover:bg-blue-700 transition-colors p-3 rounded font-semibold">
Send Message
</button>
</div>
</form>
</div>
</body>
</html>
This Blade template provides a modern, dark-themed form for users to enter a phone number and message. When submitted, the form sends the input data to the /message route, which is handled by the MessageController to send an SMS via Twilio. Using Tailwind CSS ensures the layout is responsive and visually appealing across devices, while success and error messages provide immediate feedback to users.
Step # 7 : Get Twilio Credentials.
To connect your Laravel project with Twilio, you need three key pieces of information. The Twilio SID, Auth Token, and a Twilio phone number. Follow these steps to get them.
- Sign in or create a free Twilio account here: https://www.twilio.com/try-twilio.
- From your Twilio Dashboard, note down your Account SID and Auth Token.
- Click the “Get Number” button on the dashboard to generate a Twilio phone number you can use to send messages.
Once you have these credentials, open the .env file in your Laravel project and add them like this.
TWILIO_SID="YOUR_TWILIO_SID_HERE"
TWILIO_AUTH_TOKEN="YOUR_TWILIO_AUTH_TOKEN_HERE"
TWILIO_NUMBER="YOUR_TWILIO_NUMBER_HERE"
This step ensures your Laravel application can securely authenticate with Twilio and send SMS messages using the API.
Step # 8 : Send a Test Message.
Now it’s time to send a test message. First, clear Laravel’s configuration cache.
php artisan config:clear
Then, start the development server.
php artisan serve
Open your browser and go to: http://127.0.0.1:8000. You should see the message form, where you can enter a phone number and a message.
Now try submitting the form, and make sure to use the same number that you used to create your Twilio account. Because this is a free trial Twilio account, you can only send messages to that verified number. If everything is configured correctly, you should see a success message confirming that the SMS has been sent.
You will receive the message on the mobile number associated with your Twilio account.
You can also view the sent message in your Twilio dashboard.
Now your Laravel application is fully ready to send SMS messages via Twilio!
Conclusion
By following this guide, you’ve successfully integrated Twilio SMS functionality into your Laravel 12 application. Your application can now send SMS messages using Twilio’s API, enabling smooth and reliable communication with users. The Twilio SDK simplifies message handling, while Laravel’s routing and Blade templates provide a clean, organized way to manage user input. You can further enhance this setup by adding features like message tracking, delivery status notifications, or integrating other Twilio services such as voice calls and WhatsApp messaging.
For more details, refer to the Twilio documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments