How to Send WhatsApp Messages in Laravel: Step-by-Step Guide with Twilio Integration

How to Send WhatsApp Messages in Laravel: Step-by-Step Guide with Twilio Integration

Below, I'll guide you through the process of sending WhatsApp messages in Laravel using Twilio and provide an example with a simple Blade file. Please note that you need to have a Twilio account for this example.

Step 1: Install Laravel

composer create-project --prefer-dist laravel/laravel-twillo
cd laravel-twillo

Step 2: Install Twilio SDK

composer require twilio/sdk

Step 3: Configure Twilio

Add your Twilio credentials to the .env file:

Step 4: Create a Controller

Generate a controller for WhatsApp functionality:
php artisan make:controller WhatsAppController

Step 5: Update the Controller

Open app/Http/Controllers/WhatsAppController.php and add the following code:

namespace App\Http\Controllers;

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

class WhatsAppController extends Controller
    public function sendWhatsAppMessage(Request $request)
        $to = $request->input('to'); // The recipient's phone number
        $message = $request->input('message');

        $twilio = new Client(config('services.twilio.sid'), config('services.twilio.token'));

                    "from" => "whatsapp:" . config('services.twilio.from'),
                    "body" => $message,

        return redirect()->route('whatsapp.form')->with('success', 'WhatsApp message sent successfully!');

    public function showForm()
        return view('whatsapp.form');

Step 6: Create a Blade Form

Create a Blade file at resources/views/whatsapp/form.blade.php:
<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Send WhatsApp Message</title>
    <h1>Send WhatsApp Message</h1>

    @if (session('success'))
        <p style="color: green;">{{ session('success') }}</p>

    <form action="{{ route('whatsapp.send') }}" method="post">
        <label for="to">To (WhatsApp Phone Number):</label>
        <input type="text" name="to" required>
        <label for="message">Message:</label>
        <textarea name="message" required></textarea>
        <button type="submit">Send WhatsApp Message</button>

Step 7: Define Routes

Update routes/web.php:
use App\Http\Controllers\WhatsAppController;

Route::get('/whatsapp/form', [WhatsAppController::class, 'showForm'])->name('whatsapp.form');
Route::post('/whatsapp/send', [WhatsAppController::class, 'sendWhatsAppMessage'])->name('whatsapp.send');

Step 8: Test

Run your Laravel development server:
php artisan serve
Visit http://localhost:8000/whatsapp/form in your browser, and you should see the form. Fill in the WhatsApp phone number and message, submit the form, and the WhatsApp message should be sent.
Make sure to replace placeholder values with your actual Twilio credentials.

Get The latest Coding solutions.

Subscribe to the Email Newsletter