Share this:

In today’s digital age, sending SMS messages is a powerful way to engage with your users and enhance their experience. Whether it is for notifications, updates, or security alerts, having a reliable SMS service is essential for businesses and applications alike.

In this blog post, we will go through a step-by-step tutorial on how to send SMS using Twilio, a popular communication platform, in your Laravel 10 application. We will cover the necessary steps from setting up a Twilio account to implementing the code in Laravel.

So, let’s get started!

Prerequisites:

  1. A Laravel 10 project up and running
  2. Composer installed
  3. A Twilio account (you can sign up for a free trial)

Step 1: Install Twilio SDK using Composer

To get started, you need to install the Twilio SDK in your Laravel project. Run the following command in your project directory:

composer require twilio/sdk

This will install the Twilio SDK and its dependencies.

Install Twilio SDK using Composer
Install Twilio SDK using Composer

Step 2: Set up Twilio Credentials

After signing up for a Twilio account, you will receive a unique Account SID and Auth Token. These credentials are necessary for authenticating requests to the Twilio API. Keep these credentials safe and never share them publicly.

Set up Twilio Credentials
Set up Twilio Credentials

In your Laravel project, open the .env file and add the following lines:

TWILIO_SID=your_account_sid
TWILIO_AUTH_TOKEN=your_auth_token
TWILIO_PHONE_NUMBER=your_twilio_phone_number

Replace your_account_sid, your_auth_token, and your_twilio_phone_number with the appropriate values from your Twilio account.

Set up Twilio Credentials
Set up Twilio Credentials

Step 3: Create a Twilio Service

In your Laravel project, create a new directory called Services within the app directory. Inside the Services folder, create a new file called TwilioService.php. Add the following code to this file:

<?php

namespace App\Services;

use Twilio\Rest\Client;

class TwilioService
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client(env('TWILIO_SID'), env('TWILIO_AUTH_TOKEN'));
    }

    public function sendSMS($to, $message)
    {
        return $this->client->messages->create($to, [
            'from' => env('TWILIO_PHONE_NUMBER'),
            'body' => $message,
        ]);
    }
}

This service class initializes the Twilio client and has a method called sendSMS that takes the recipient’s phone number and the message as arguments.

Create a Twilio Service
Create a Twilio Service

Step 4: Register the Twilio Service

In the app/Providers/AppServiceProvider.php file, add the following use statement at the top of the file:

use App\Services\TwilioService;

Then, register the TwilioService in the register method:

public function register()
{
    $this->app->bind(TwilioService::class, function ($app) {
        return new TwilioService();
    });
}

Your AppServiceProvider should now look like this:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Services\TwilioService;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        $this->app->bind(TwilioService::class, function ($app) {
            return new TwilioService();
        });
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        //
    }
}
Register the Twilio Service
Register the Twilio Service

Step 5: Implement SMS Sending in Your Controller

Now that the TwilioService is set up, you can use it in your Laravel controllers. Here’s an example of how to use the service in a controller:

<?php

namespace App\Http\Controllers;

use App\Services\TwilioService;
use Illuminate\Http\Request;

class SMSController extends Controller
{
    protected $twilioService;

    public function __construct(TwilioService $twilioService)
    {
        $this->twilioService = $twilioService;
    }

    public function sendSMS(Request $request)
    {
        $this->validate($request, [
            'phone' => 'required',
            'message' => 'required',
        ]);

        $response = $this->twilioService->sendSMS($request->phone, $request->message);

        if ($response->sid) {
            return response()->json(['success' => true, 'message' => 'SMS sent successfully.']);
        } else {
 
            return response()->json(['success' => false, 'message' => 'Failed to send SMS.']);
        }
    }
}
Implement SMS Sending in Your Controller
Implement SMS Sending in Your Controller

In this example, the SMSController has a sendSMS method that takes a Request object. The request should contain the recipient’s phone number and the message text. The method then calls the sendSMS method of the TwilioService and returns a JSON response indicating the success or failure of the operation.

Step 6: Create Routes for the SMS Sending

To make the sendSMS method accessible, create a route in the routes/web.php or routes/api.php file, depending on your project setup:

use App\Http\Controllers\SMSController;

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

Now, you can send a POST request to the /send-sms endpoint with the required parameters to send an SMS using Twilio in your Laravel 10 application.

Create Routes for the SMS Sending
Create Routes for the SMS Sending

Testing

If you prefer to test the SMS sending functionality manually using your browser, you can do so by following these steps:

Start Laravel Development Server

Open the terminal, navigate to your Laravel project directory, and run the following command to start the Laravel development server:

php artisan serve

The server will start, and you’ll see a message with the address where your application is running, which is usually http://127.0.0.1:8000.

Create a Simple HTML Form

To test the SMS sending functionality, create a simple HTML form that sends a POST request to the /send-sms route. You can create a new Blade template for this or add the form to an existing template. Here’s an example of a basic form:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send SMS - LaravelTuts</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1 class="mt-5">Send SMS using Twilio and Laravel 10 - LaravelTuts</h1>
        <form action="{{ url('/send-sms') }}" method="POST" class="mt-4">
            @csrf
            <div class="mb-3">
                <label for="phone" class="form-label">Phone Number:</label>
                <input type="text" name="phone" id="phone" class="form-control" required>
            </div>
            <div class="mb-3">
                <label for="message" class="form-label">Message:</label>
                <textarea name="message" id="message" class="form-control" required></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Send SMS</button>
        </form>
    </div>
</body>
</html>

Add a Route for the Form

To display the form, create a new route in the routes/web.php file:

Route::get('/sms-form', function () {
    return view('sms_form');
});

Test the Form

Now that the form and route are set up, open your browser and navigate to the following URL:

http://127.0.0.1:8000/sms-form
Laravel 10 Send SMS using Twilio Tutorial Example
Laravel 10 Send SMS using Twilio Tutorial Example

Fill out the form with a valid phone number and a message, then click the “Send SMS” button. If everything is set up correctly, you should see a JSON response indicating the success or failure of the SMS sending process.

Laravel 10 Send SMS using Twilio Tutorial Example
Laravel 10 Send SMS using Twilio Tutorial Example
Laravel 10 Send SMS using Twilio Tutorial Example
Laravel 10 Send SMS using Twilio Tutorial Example

Please note that if you are using a Twilio trial account, you can only send SMS messages to verified phone numbers. To send messages to other numbers, you’ll need to upgrade your Twilio account.

Conclusion:

In this tutorial, we walked through the process of integrating Twilio into a Laravel 10 application to send SMS messages.

With just a few lines of code, you can now leverage the power of Twilio to send SMS notifications and updates to your users. The flexibility of the Laravel framework combined with the robustness of the Twilio platform can greatly enhance your application’s communication capabilities.

Happy coding!

Share this:

Categorized in: