Laravel 10 Send SMS using Twilio api

Hello guy,

Certainly! I can provide you with a basic tutorial on sending SMS using Twilio in Laravel. However, please note that as of my knowledge cutoff in September 2021, Laravel 8 was the latest version available. The code examples I provide should work for Laravel 8, but there may be slight changes required for future versions like Laravel 10.

Here's a step-by-step guide on how to send SMS using Twilio in Laravel:

Step 1: Install Twilio SDK 

 In your Laravel project, open a terminal and navigate to the project's root directory. Then, install the Twilio SDK using Composer by running the following command:

composer require twilio/sdk

Step 2: Configure Twilio Credentials 

 After the SDK installation, you need to configure your Twilio credentials. Open the .env file in the root directory of your Laravel project 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

Replace your_twilio_account_sid, your_twilio_auth_token, and your_twilio_phone_number with your actual Twilio account SID, auth token, and phone number respectively.

Step 3: Create a Controller

Next, create a controller that will handle the SMS sending logic. Run the following command in your terminal to generate a new controller:

php artisan make:controller SMSController

Open the app/Http/Controllers/SMSController.php file and replace the code with the following example:

<?php

namespace App\Http\Controllers;

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

class SMSController extends Controller
{
    public function sendSms(Request $request)
    {
        $to = $request->input('to');
        $message = $request->input('message');

        $twilioSid = config('app.twilio_sid');
        $twilioToken = config('app.twilio_auth_token');
        $twilioPhoneNumber = config('app.twilio_phone_number');

        $twilio = new Client($twilioSid, $twilioToken);

        try {
            $twilio->messages->create(
                $to,
                [
                    'from' => $twilioPhoneNumber,
                    'body' => $message,
                ]
            );
            
            return response()->json(['message' => 'SMS sent successfully.']);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to send SMS.'], 500);
        }
    }
}

This controller defines a sendSms method that receives the recipient's phone number ($to) and the message content ($message) as inputs. It uses the Twilio SDK to send an SMS using the provided credentials.

Step 4: Define Routes

Open the routes/web.php file and add the following route definition:

Route::post('/send-sms', 'App\Http\Controllers\SMSController@sendSms');

This route maps the sendSms method in the SMSController to the /send-sms URL, and it expects a POST request.

Step 5: Create a Form

In your Laravel project, create a new view file called sendsms.blade.php in the resources/views directory. Add the following code to the file:

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

Step 6: Test the Application

You can now run your Laravel application and test the SMS sending functionality. Start the development server by running the following command in your terminal:

php artisan serve

Visit http://localhost:8000/sendsms in your web browser, and you should see a form to send an SMS. Enter the recipient's phone number and the message, then click the "Send SMS" button.

The form will submit a POST request to the /send-sms URL, which will trigger the sendSms method in the SMSController. If everything is configured correctly, the SMS will be sent using Twilio, and you should see a success message.

That's it! You've successfully implemented SMS sending using Twilio in Laravel. Remember to handle any exceptions and errors appropriately in your production application.

Please note that this tutorial assumes you have already set up a Twilio account and have valid credentials. If you don't have a Twilio account, you can sign up for free at https://www.twilio.com/.

I hope this helps! Let me know if you have any further questions.