Laravel 11 - How to Send SMS using Twilio

Touseef Afridi
25 Sep 24

Laravel 11 - How to Send SMS using Twilio

In this tutorial, we will explore how to send SMS in Laravel 11 using Twilio, a reliable tool for seamless communication in applications.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide provides a step-by-step process for integrating Twilio SMS functionality into a Laravel project. It starts with setting up a new Laravel project or using an existing one, followed by installing the Twilio SDK. A controller is created to handle SMS sending, and routes are defined to display the message form and process submissions. A Blade view is set up with a form for users to enter a phone number and message. The guide then covers retrieving Twilio credentials and storing 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.

Step # 1 : Create a New Laravel Project or Use an Existing One.

If you have Laravel installed globally, you can create a new project by running.
laravel new message
Or
Alternatively, you can use Composer to generate the project.
composer create-project laravel/laravel --prefer-dist message
During the setup process, choose the following options when prompted.
  • Starter Kit: Select None to install Laravel without authentication scaffolding.
  • Testing Framework: Choose Pest for a minimalistic testing setup.
  • Database: Select MySQL as the database for your application.
  • Run Migrations: Type Yes to execute the default database migrations.

We now have a Laravel project named message with a minimal setup. It uses Pest for testing, MySQL as the database, and has applied default migrations. Since we selected None for the Starter Kit, the project does not include any authentication scaffolding, keeping it lightweight and flexible for customization.

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/message
This allows you to manage dependencies, run commands, and start development.

Step # 3 : Install Twilio package.

Run the following command to install the Twilio SDK.
composer require twilio/sdk
This package allows Laravel to integrate Twilio's messaging services, enabling functionalities like sending SMS, making calls, and handling communications efficiently. It simplifies interaction with Twilio's API, ensuring seamless message delivery.

Step # 4 : Create a controller.

Generate the MessageController by running the following command.
php artisan make:controller MessageController
Then, update the controller 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.
  $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 step creates MessageController, which manages SMS sending through Twilio. It includes an index method to display the form and a store method to send messages using Twilio credentials from the .env file. This ensures a structured approach to handling message delivery while keeping credentials secure.

Step # 5 : Define Routes.

Import the MessageController and define the necessary routes.
use App\Http\Controllers\MessageController;
Route::get('/', [MessageController::class, 'index']);
Route::post('/message', [MessageController::class, 'store']);
These routes handle displaying the message form (index method) and processing SMS sending (store method) using Twilio. Defining these routes ensures seamless communication between the frontend and backend, enabling users to send messages efficiently.

Step # 6 : Create a view.

Create a Blade file named message.blade.php and include the following HTML to display a form for sending messages.
<!DOCTYPE html>
<html>
<head>
    <title>Code Shotcut - Send Message in Laravel</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <div class="card">
                    <div class="card-header">
                        <h2>Send Message</h2>
                    </div>
                    <div class="card-body">
                        @if ($message = Session::get('success'))
                        <div class="alert alert-success alert-block">
                            <strong>{{ $message }}</strong>
                        </div>
                        @endif
                        @if ($message = Session::get('error'))
                        <div class="alert alert-danger alert-block">
                            <strong>{{ $message }}</strong>
                        </div>
                        @endif
                        <form method="POST" action="{{ url('/message') }}">
                            {{ csrf_field() }}
                            <div class="mb-3">
                                <label for="phone" class="form-label">Phone:</label>
                                <input type="text" name="phone" id="phone" class="form-control @error('phone') is-invalid @enderror" placeholder="Phone Number">
                                @error('phone')
                                <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                            <div class="mb-3">
                                <label for="message" class="form-label">Message:</label>
                                <textarea name="message" id="message" class="form-control @error('message') is-invalid @enderror" placeholder="Enter Message"></textarea>
                                @error('message')
                                <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                            <div class="mb-3">
                                <button type="submit" class="btn btn-success">Send Message</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
This Blade template provides a simple form for users to input a phone number and message. Upon submission, the form sends data to the /message route, where it is processed to send an SMS via Twilio. Bootstrap styling ensures a clean and responsive layout, enhancing the user experience across different devices.

Step # 7 : Get Twilio credentials.

You can get the required keys by following these steps.
  • Sign in or create a Twilio account at (https://www.twilio.com/try-twilio).
  • From the Twilio Dashboard, retrieve the Twilio SID, Auth Token & Twilio Number (Click the Get Number button).



Open the .env file in your Laravel project and add.
TWILIO_SID="YOUR_TWILIO_SID_HERE"
TWILIO_AUTH_TOKEN="YOUR_TWILIO_AUTH_TOKEN_HERE"
TWILIO_NUMBER="YOUR_TWILIO_NUMBER_HERE"
This step configures Twilio credentials in your Laravel project, allowing secure authentication for sending messages via Twilio's API.

Step # 8 : It's time to test.

Now, it's time to test the setup. Clear the configuration cache.
php artisan config:clear
Start the Laravel development server.
php artisan serve
Open your browser and access the below URL.
127.0.0.1:8000
You should see the message form, where you can enter a phone number and a message. After submitting the form, Laravel will process the request, and Twilio will send the SMS. If the message is delivered successfully, you’ll see a confirmation; otherwise, check for errors, ensure your Twilio credentials are correct, and verify that your Twilio number is enabled for messaging. This final step confirms that your Laravel application is properly integrated with Twilio, allowing you to send messages seamlessly.





Conclusion

By following this guide, you've successfully integrated Twilio SMS functionality into your Laravel application. Your application can now send SMS messages using Twilio's API, allowing seamless communication with users. The Twilio SDK simplifies message handling, while Laravel's routing and Blade templates provide a structured way to manage user input. You can further enhance this setup by implementing message tracking, adding delivery status updates, or integrating additional Twilio features such as voice calls and WhatsApp messaging.
For more details, refer to the Twilio documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering