Laravel 12 - How to Send WhatsApp Notifications / Messages with Twilio.

Touseef Afridi
31 Dec 25

Laravel 12 - How to Send WhatsApp Notifications / Messages with Twilio.

In this tutorial, we will learn how to send WhatsApp messages and notifications in Laravel 12 using Twilio, enabling your application to communicate seamlessly with users.

Quick Overview

This guide walks you through integrating Twilio’s WhatsApp API with a Laravel 12 application. It covers setting up a new Laravel project, installing the Twilio SDK, creating a controller to handle WhatsApp messages, defining the required routes, and building a responsive form for sending messages. You’ll also configure your Twilio credentials, enable WhatsApp sandbox sync, and test the integration by sending a message to ensure everything works correctly.

Step # 1 : Set Up a Laravel 12 Application to Begin Development.

To begin working with Laravel 12, you’ll first need an application environment in place. You can either spin up a brand-new Laravel project or continue inside an existing codebase, depending on your workflow. If the Laravel Installer is already available on your system, creating a new project is quick and straightforward. Simply run the following command to generate a project named WhatsApp.
laravel new whatsapp
If you don’t have the Laravel Installer installed globally, you can achieve the same result using Composer. This approach directly scaffolds the framework without any interactive prompts.
composer create-project laravel/laravel --prefer-dist whatsapp
When creating the project through Composer, Laravel automatically sets up a minimal project structure. In comparison, the Laravel Installer guides you through a short configuration process. For this setup, choose the following.
  • Starter Kit: Go with None to keep the project lightweight and focused purely on the Laravel framework.
  • Testing Framework: Select Pest for a modern, developer-friendly testing experience.
  • Database: Use MySQL as the main database driver for your application.
  • Run Migrations: Confirm with yes so Laravel executes the default migrations right away.
  • Frontend Dependencies: Choose Yes to have Laravel automatically install the required frontend packages.

Once the setup finishes, Laravel generates the whatsapp project directory, installs all required dependencies, and runs the default database migrations. With everything configured and Pest ready for testing, your Laravel 12 application is fully prepared for further development and customization.

Step # 2 : Navigate to Your Project.

Open a terminal (like Git Bash) and switch to your Laravel project's root directory with.
cd c:/xampp/htdocs/whatsapp
This sets your terminal to the project folder so you can run Artisan commands and manage your Laravel 12 application.

Step # 3 : Install the Twilio SDK Package.

To enable messaging and call capabilities in your Laravel 12 project, install the official Twilio SDK by running.
composer require twilio/sdk
Once installed, the Twilio package equips your Laravel 12 application to send SMS messages, WhatsApp messages, make voice calls, and interact with Twilio’s API. This step lays the groundwork for adding powerful communication features to your app.

Step # 4 : Create a WhatsApp Controller.

To handle WhatsApp message sending, start by creating a new controller with the following command.
php artisan make:controller WhatsAppController
Next, update the WhatsAppController with the code below.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twilio\Rest\Client;
use Exception;
class WhatsAppController extends Controller
{
    // Show the WhatsApp message form
    public function index()
    {
        return view('whatsapp');
    }
    // Handle form submission and send WhatsApp message
    public function store(Request $request)
    {
        // Twilio credentials from environment
        $twilioSid = env('TWILIO_SID');
        $twilioAuthToken = env('TWILIO_AUTH_TOKEN');
        $twilioWhatsappNumber = 'whatsapp:' . env('TWILIO_WHATSAPP_NUMBER');
        // Recipient number must follow WhatsApp format:
        // whatsapp:+CountryCodePhoneNumber (e.g., whatsapp:+123456789)
        $to = 'whatsapp:' . $request->phone;
        // Message content from form input
        $message = $request->message;
        // Initialize Twilio client
        $client = new Client($twilioSid, $twilioAuthToken);
        try {
            // Send the WhatsApp message
            $message = $client->messages->create(
                $to,
                [
                    'from' => $twilioWhatsappNumber,
                    'body' => $message
                ]
            );
            return "Message sent successfully! SID: " . $message->sid;
        } catch (Exception $e) {
            // Return error message if sending fails
            return "Error sending message: " . $e->getMessage();
        }
    }
}
The WhatsAppController is responsible for sending messages through Twilio in your Laravel 12 application. The index() method displays a form for users to input a phone number and message, while the store() method processes the submission, retrieves Twilio credentials from the .env file, formats the recipient’s number, and sends the message via Twilio’s API. It returns a success message with the message SID or an error if the sending fails, enabling dynamic WhatsApp messaging in your app.

Step # 5 : Set Up Routes for WhatsApp Messaging.

Next, import the WhatsAppController and define the routes in your routes/web.php file.
use App\Http\Controllers\WhatsAppController;
Route::get('/', [WhatsAppController::class, 'index']);
Route::post('whatsapp', [WhatsAppController::class, 'store']);
The GET route (/) loads the index() method, displaying the form for users to enter a phone number and message. The POST route (whatsapp) calls the store() method, handling the form submission and sending the WhatsApp message via Twilio. This configuration allows users to easily access the form and submit messages from your Laravel 12 application.

Step # 6 : Create a WhatsApp Messaging View.

Create a Blade file named whatsapp.blade.php and include the following HTML for the message form.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 12 - Cose Shotcut Send WhatsApp Message</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 text-gray-100 min-h-screen flex items-center justify-center">
    <div class="w-full max-w-lg p-6 bg-gray-800 rounded-lg shadow-lg">
        <h1 class="text-xl font-bold mb-4 text-center">Code Shotcut - Send a WhatsApp Message</h1>
        <p class="text-gray-400 mb-6 text-center">Enter the recipient's phone number and your message below to send it via Twilio.</p>
        @if ($message = Session::get('success'))
        <div class="bg-green-600 text-white p-3 rounded mb-4">
            {{ $message }}
        </div>
        @endif
        @if ($message = Session::get('error'))
        <div class="bg-red-600 text-white p-3 rounded mb-4">
            {{ $message }}
        </div>
        @endif
        <form method="POST" action="{{ url('/whatsapp') }}">
            @csrf
            <div class="mb-4">
                <label for="phone" class="block mb-1 font-medium">Phone Number:</label>
                <input type="text" name="phone" id="phone"
                       class="w-full p-2 rounded bg-gray-700 border border-gray-600 text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 @error('phone') border-red-500 @enderror"
                       placeholder="e.g., +1234567890">
                @error('phone')
                <span class="text-red-500 text-sm mt-1">{{ $message }}</span>
                @enderror
            </div>
            <div class="mb-4">
                <label for="message" class="block mb-1 font-medium">Message:</label>
                <textarea name="message" id="message"
                          class="w-full p-2 rounded bg-gray-700 border border-gray-600 text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 @error('message') border-red-500 @enderror"
                          placeholder="Type your message here..."></textarea>
                @error('message')
                <span class="text-red-500 text-sm mt-1">{{ $message }}</span>
                @enderror
            </div>
            <div class="text-center">
                <button type="submit"
                        class="px-6 py-2 bg-green-600 hover:bg-green-700 rounded text-white font-semibold transition">Send Message</button>
            </div>
        </form>
    </div>
</body>
</html>
This Blade template provides a simple form where users can enter a phone number and message to send via Twilio. The form handles input validation and displays success or error messages based on the response. Once submitted, the data is sent to the /whatsapp route, where your controller processes it and delivers the WhatsApp message dynamically within your Laravel 12 application.

Step # 7 : Get Twilio SDK Credentials.

To send WhatsApp messages through Twilio, you need to obtain your account credentials and WhatsApp number. Follow these steps.
  1. Sign in or create a Twilio account at: https://www.twilio.com/try-twilio.

  2. From the Twilio Dashboard, get your Account SID and Auth Token.



  3. Twilio provides a separate number for WhatsApp. Navigate to Messaging Overview Try WhatsApp to get your WhatsApp-enabled number.



Open your Laravel .env file and add 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"
Make sure to replace the placeholders with your actual Twilio credentials. Once configured, your Laravel 12 application can securely connect to Twilio’s API and send WhatsApp messages dynamically.

Step # 8 : Enable WhatsApp Sandbox Sync.

To authorize your Twilio account to send WhatsApp messages, you need to sync your WhatsApp account with the Twilio Sandbox. Follow these steps.
  1. Get the Code – In the Twilio Dashboard, navigate to Messaging Overview Try WhatsApp to find your unique sandbox code.



  2. Send the Code – Open WhatsApp on your phone/web and send the message join YOUR_CODE_HERE to the Twilio WhatsApp number provided in the dashboard.



  3. Receive Confirmation – You will get a reply confirming that your WhatsApp account is now synced with Twilio.



Once this process is complete, your Twilio account is authorized, and your Laravel 12 application can successfully send WhatsApp messages.

Step # 9 : Test Your WhatsApp Integration.

Now it’s time to verify that everything is working. Start the Laravel development server by running.
php artisan serve
Open your browser and go to http://127.0.0.1:8000. Use the form to send a WhatsApp message.

If everything is set up correctly, you’ll see a success message on the page, and the message will appear in your WhatsApp.


If it doesn’t work, double-check your Twilio credentials in the .env file and ensure your WhatsApp number is synced with the Twilio Sandbox.

Conclusion

By following this guide, you’ve successfully integrated WhatsApp messaging into your Laravel 12 application using Twilio. Your app can now send messages through a straightforward form, utilizing Twilio’s API for communication. This foundation can be expanded with features like automated replies, message tracking, or connecting with other services. If you encounter any issues, double-check your Twilio credentials and ensure your WhatsApp account is properly synced.
For further information, refer to Twilio’s official 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