Laravel

Laravel 10 Send SMS using Twilio Tutorial Example

Share your learning

Today we will discuss about how to send SMS using Twilio in Laravel.

In today’s digital world, communicating with users through SMS has become an essential aspect of web applications. Laravel, one of the most popular PHP frameworks, provides developers with powerful tools to build feature-rich applications quickly. 

Twilio, on the other hand, is a cloud communications platform that enables developers to send SMS and make voice calls programmatically. 

In this tutorial, we will explore how to send SMS using Twilio in a Laravel 10 application.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. PHP and Composer installed on your machine.
  2. Laravel 10 installed and set up.
  3. A Twilio account (you can sign up for a free trial at https://www.twilio.com/try-twilio).

Step 1: Install Twilio SDK

To integrate Twilio with Laravel, we need to install the Twilio PHP SDK. Open your terminal and navigate to your Laravel project directory. Run the following command to install the Twilio SDK via Composer:

composer require twilio/sdk

Step 2: Configure Twilio Credentials

After installing the Twilio SDK, you need to set up your Twilio credentials. Open the .env file in your Laravel project root directory and add the following lines:

TWILIO_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_PHONE_NUMBER=your_twilio_phone_number

Make sure to replace your_twilio_account_sid, your_twilio_auth_token, and your_twilio_phone_number with your actual Twilio credentials. You can find your Twilio Account SID and Auth Token on the Twilio Dashboard.

Step 3: Create a Controller

Next, let’s create a controller that will handle sending SMS. Run the following command in your terminal:

php artisan make:controller TwilioController

This command will create a new controller file named TwilioController.php in the app/Http/Controllers directory.

Step 4: Implement the twilio SMS Sending Logic in laravel

Open the TwilioController.php file and add the following code:

<?php

namespace App\Http\Controllers;

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

class TwilioController extends Controller
{
    public function sendSMS(Request $request)
    {
        $message = $request->input('message');
        $toPhoneNumber = $request->input('to_phone_number');

        $twilioSID = env('TWILIO_SID');
        $twilioAuthToken = env('TWILIO_AUTH_TOKEN');
        $twilioPhoneNumber = env('TWILIO_PHONE_NUMBER');

        $twilio = new Client($twilioSID, $twilioAuthToken);

        try {
            $twilio->messages->create(
                $toPhoneNumber,
                [
                    'from' => $twilioPhoneNumber,
                    'body' => $message,
                ]
            );

            return response()->json(['message' => 'SMS sent successfully.']);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to send SMS.']);
        }
    }
}

In this code, we have a sendSMS method that takes the message and the recipient phone number as input. It then fetches the Twilio credentials from the .env file, creates a new instance of the Twilio Client, and sends the SMS using the messages->create() method.

Step 5: Define Routes

Now, we need to define a route that will trigger the sendSMS method in our controller. Open the routes/web.php file and add the following route:

use App\Http\Controllers\TwilioController;

Route::post('/send-sms', [TwilioController::class, 'sendSMS']);

Step 6: Create a View (Optional)

If you wish to provide a user interface to send SMS, you can create a view with a form to enter the message and phone number. Create a new Blade view file, for example, sendsms.blade.php, in the resources/views directory. Add the following code to the view:

<!DOCTYPE html>
<html>
<head>
    <title>Send SMS using Twilio</title>
</head>
<body>
    <h1>Send SMS using Twilio</h1>
    <form action="/send-sms" method="post">
        @csrf
        <label for="to_phone_number">To Phone Number:</label>
        <input type="text" id="to_phone_number" name="to_phone_number" required>
        <br>
        <label for="message">Message:</label>
        <textarea id="message" name="message" required></textarea>
        <br>
        <button type="submit">Send SMS</button>
    </form>
</body>
</html>

Step 7: Test the Application

Now, you can test the application. Start the development server by running the following command:

php artisan serve

Visit your application in the browser, and if you created the view in Step 6, go to /sendsms to access the form.

Enter the recipient’s phone number and the message, and click on the “Send SMS” button. The application will send the SMS using Twilio, and you should see a success message.

Conclusion

In this tutorial, we have learned how to send SMS using Twilio in a Laravel 10 application. By integrating Twilio with Laravel, you can easily send SMS notifications, alerts, and more to your users. This functionality can significantly enhance the user experience and keep your users informed in real-time.

Remember to handle any exceptions that may occur during the SMS sending process and consider adding validation to ensure the phone number and message inputs are correct.

Happy coding!

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

7 months ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

7 months ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

9 months ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

9 months ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

9 months ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

9 months ago