Laravel 11 - How to Send WhatsApp Message Using Twilio.

Touseef Afridi
24 Sep 24

Laravel 11 - How to Send WhatsApp Message Using Twilio.

In this tutorial, we'll explore how to send WhatsApp notifications or messages in Laravel 11, enabling seamless communication with users and enhancing engagement.


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


Quick Overview

This guide walks through integrating Twilio's WhatsApp API with Laravel. It covers setting up the project, installing the Twilio SDK, creating a controller, defining routes, and building a simple form for sending messages. You'll also configure Twilio credentials, enable WhatsApp messaging, sync with Twilio, and test the setup by sending a message.

Step # 1 : Create fresh Laravel project or use existing project.

If Laravel is installed globally, you can create a new project using.
laravel new whatsapp
Or
Alternatively, use Composer to create the project.
composer create-project laravel/laravel --prefer-dist whatsapp
During the setup process, make the following selections when prompted.
  • Starter Kit – Choose None
  • Testing Framework – Select Pest
  • Database – Select MySQL
  • Run Database Migration – Type yes

This will set up a fresh Laravel project named whatsapp without a starter kit. If Laravel is installed globally, the laravel new command is a quick way to create a project. Otherwise, use Composer's create-project command. The setup ensures that the database is initialized with migrations and Pest is selected as the testing framework.

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and move to your Laravel project's root folder using the following command.
cd c:/xampp/htdocs/whatsapp
This command changes the current working directory to your Laravel project's location, allowing you to run Artisan commands and manage the application.

Step # 3 : Install the Twilio Package.

To integrate Twilio into your Laravel project, install the Twilio SDK by running the following command.
composer require twilio/sdk
This command pulls the Twilio SDK into your project via Composer, enabling you to send SMS, make calls, and interact with Twilio's API from your Laravel application.

Step # 4 : Create a Controller.

To manage WhatsApp message sending, create a new controller using the following command.
php artisan make:controller WhatsappController
Then, update the WhatsappController with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twilio\Rest\Client;
use Exception;
class WhatsAppController extends Controller
{
 // Method to return the WhatsApp view
 public function index()
 {
  return view('whatsapp');
 }
 // Method to handle form submission and send a WhatsApp message via Twilio
 function store(Request $request)
 {
        // Note: Both 'from' and 'to' numbers should be formatted as:
        // whatsapp:+CountryCodePhoneNumber (e.g., whatsapp:+123456789)
        // Get Twilio credentials and WhatsApp number from environment variables
  $twilioSid = env('TWILIO_SID');
  $twilioAuthToken = env('TWILIO_AUTH_TOKEN');
  $twilioWhatsappNumber = 'whatsapp:'.env('TWILIO_WHATSAPP_NUMBER');
  // Get the recipient's WhatsApp number and message content from the request
  $to = 'whatsapp:'.$request->phone;
  $message = $request->message;
  // Create a new Twilio client using the SID and Auth Token
  $client = new Client($twilioSid, $twilioAuthToken);
  try {
   // Send the WhatsApp message using Twilio's API
   $message = $client->messages->create(
    $to,
    array(
     'from' => $twilioWhatsappNumber,
     'body' => $message
    )
   );
   // Return success message with the message SID for reference
   return "Message sent successfully! SID: " . $message->sid;
  } catch (Exception $e) {
    // Catch any errors and return the error message
   return "Error sending message: " . $e->getMessage();
  }
 }
}
This controller is responsible for sending WhatsApp messages via Twilio. It includes two methods index() and store(Request $request). The index() method returns the whatsapp view, which contains a form where users can enter a phone number and message. The store() method processes the form submission by retrieving Twilio credentials from the .env file, formatting the recipient’s phone number in WhatsApp’s required format, and initializing Twilio’s Client using the provided credentials. It then attempts to send a message via Twilio's API. If successful, it returns a confirmation message with a unique message SID; otherwise, it catches the exception and returns an error message. This setup allows for dynamically sending WhatsApp messages within a Laravel application.

Step # 5 : Define and Update Routes.

Import the WhatsAppController and define the necessary routes in your routes/web.php file.
use App\Http\Controllers\WhatsAppController;
Route::get('/', [WhatsAppController::class, 'index']);
Route::post('whatsapp', [WhatsAppController::class, 'store']);
These routes handle WhatsApp message interactions. The GET route (/) loads the index() method, which displays the form where users can enter a phone number and message. The POST route (whatsapp) triggers the store() method, processing the form submission and sending a WhatsApp message via Twilio. This setup ensures that users can access the message form and submit requests efficiently.

Step # 6 : Create a View.

Create a Blade file named whatsapp.blade.php and include the following HTML to display a form for sending WhatsApp messages.
<!DOCTYPE html>
<html>
<head>
    <title>Code Shotcut - Send WhatsApp Message in Laravel 11</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 WhatsApp 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('/whatsapp') }}">
                            {{ 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 sending WhatsApp messages. It includes fields for a phone number and message, with Bootstrap 5 for styling. On submission, it sends a POST request to the /whatsapp route for processing via Twilio. The form also handles validation and displays success or error messages based on the response.

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.
  • Get Twilio Credentials – Retrieve your Twilio SID and Auth Token from the Twilio Dashboard.
  • Enable WhatsApp – Twilio provides a separate number for WhatsApp. Navigate to Messaging Overview Try WhatsApp to get it.



Open the .env file and update it with the following lines.
TWILIO_SID="YOUR_TWILIO_SID_HERE"
TWILIO_AUTH_TOKEN="YOUR_TWILIO_AUTH_TOKEN_HERE"
TWILIO_WHATSAPP_NUMBER="YOUR_TWILIO_WHATSAPP_NUMBER_HERE"
This setup enables your Laravel application to send WhatsApp messages using Twilio's API.

Step # 8 : Enable Sync.

To enable synchronization, send a specific code from your WhatsApp account to your Twilio WhatsApp number.
Get the Code – Navigate to MessagingOverviewTry WhatsApp to find the code.

Send the Code – Open WhatsApp and send (join "YOUR CODE HERE") to your Twilio WhatsApp number.


Receive Confirmation – You will get a response confirming that WhatsApp is now synced with Twilio.

This step ensures that your Twilio account is authorized to send WhatsApp messages.

Step # 9 : It's time to test.

Start the Laravel development server.
php artisan serve.
Open your browser and go to 127.0.0.1:8000, then test the form by sending a WhatsApp message.

You'll receive a success message. Check your WhatsApp to confirm.


If everything is set up properly, submitting the form will send a WhatsApp message via Twilio. If you run into any issues, double-check your Twilio credentials and ensure WhatsApp is enabled for your number.

Conclusion

By following this guide, you've successfully set up WhatsApp messaging in Laravel using Twilio. Your application can now send messages through a simple form, leveraging Twilio’s API. This setup can be extended with features like automated responses, message tracking, or integration with other services. If any issues arise, verify your Twilio credentials and ensure WhatsApp sync is enabled.
For more details, explore Twilio’s API 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