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!


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

Two commands to create fresh laravel project
Global Command : laravel new whatsapp
Or use
Non Global Command : composer create-project laravel/laravel --prefer-dist whatsapp

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
Git Bash : cd c:xampp/htdocs/whatsapp

Step # 3 : Let's install Twilio package.

Run the following command to install the package.
Command : composer require twilio/sdk

Step # 4 : Create a controller.

Run the following command to create the WhatsappController.
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();
  }
 }
}

Step # 5 : Let's create & update routes.

Import WhatsAppController class, create and update route.
use App\Http\Controllers\WhatsAppController;
Route::get('/', [WhatsAppController::class, 'index']);
Route::post('whatsapp', [WhatsAppController::class, 'store']);

Step # 6 : Create a view.

Create a Blade file named whatsapp.blade.php and include the following HTML, which contains a form for sending a whatsapp message to a specific phone number.
<!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>

Step # 7 : Get Twilio credentials.

Login or create Twilio account.
Link : https://www.twilio.com
Obtain your Twilio credentials and enable WhatsApp (note that the Twilio WhatsApp number is different from the regular number displayed on your dashboard).
You can get the Twilio Auth SID & Auth Token from the Twilio account Dashboard.

Get your Twilio WhatsApp number by navigating to Messaging -> Overview -> Try WhatsApp.

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"

Step # 8 : Enable Sync.

First, send the provided code from your WhatsApp account to your Twilio WhatsApp number to enable synchronization.
Access the code
Messaging -> Overview -> Try WhatsApp.
join "YOUR CODE HERE".


Send the code via WhatsApp.



You will receive a response.

Step # 9 : It's time to test.

Now we should be able to send message or code using the form.
Start the Laravel development server.
Command : php artisan serve.
Access below URL
127.0.0.1:8000

You will receive a success message.



Check your whatsapp.




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