How to Send WhatsApp Messages With Laravel?

How to Send WhatsApp Messages With Laravel

WhatsApp is one of the most widely used messaging platforms globally. Integrating it with your Laravel application can enhance customer engagement, improve notifications, and support real-time communication.

Hire laravel Developer

Use Cases for WhatsApp in Laravel

  • Order confirmations & shipping alerts
  • OTPs and verification codes
  • Customer support automation
  • Appointment reminders
  • Promotional broadcasts (requires WhatsApp Business Approval)

In this blog, we’ll show you how to send WhatsApp messages using Laravel with the help of Twilio, one of the most popular APIs for WhatsApp Business integration.

Whatsapp_api

Why Twilio?

Twilio is a cloud-based communication platform that enables developers to easily integrate voice, text messaging, and video features into their apps. It’s known for being both easy to use and highly scalable, with support for several popular programming languages. With Twilio’s API, businesses can send SMS messages, make phone calls, or add two-factor authentication with just a few lines of code.

In this example, we will use the third-party package “twilio/sdk” to send WhatsApp messages to users.

Steps to Send WhatsApp Messages with Laravel using Twilio:

Step 1: Install Laravel

Run the below command to install Laravel

composer create-project laravel/laravel example-app

Step 2: Set up a Twilio Account

First, you need to create and add a phone number. Then you can easily get the account SID, Token, and Number.

Create an Account from here: www.twilio.com 

Next, add a Twilio Phone Number

Next, you can get account SID, Token, and Number and add to the .env file as below:

.env

TWILIO_SID=your_twilio_account_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_WHATSAPP_NUMBER=your_twilio_whatsapp_number

Step 3: Install twilio/sdk Package

Run the below command

composer require twilio/sdk

Step 4: Create route

routes/web.php

Route::get('whatsapp', [WhatsAppController::class, 'index']);
Route::post('whatsapp', [WhatsAppController::class, 'store'])->name('whatsapp.post');

Step 5: Create Controller

app/Http/Controllers/WhatsAppController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twilio\Rest\Client;
use Exception;

class WhatsAppController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('whatsapp');
    }
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $twilioSid = env('TWILIO_SID');
        $twilioToken = env('TWILIO_AUTH_TOKEN');
        $twilioWhatsAppNumber = env('TWILIO_WHATSAPP_NUMBER');
        $recipientNumber = $request->phone;
        $message = $request->message;
        try {
            $twilio = new Client($twilioSid, $twilioToken);
            $twilio->messages->create(
                $recipientNumber,
                [
                    "from" => "whatsapp:+". $twilioWhatsAppNumber,
                    "body" => $message,
                ]
            );
            return back()->with(['success' => 'WhatsApp message sent successfully!']);
        } catch (Exception $e) {
            return back()->with(['error' => $e->getMessage()]);
        }
    }
}

Step 6: Create Blade File

resources/views/whatsapp.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Sent message</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <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">
  
        <div class="row">
            <div class="col-md-9">
  
                <div class="card">
                  <div class="card-header">
                    <h2>Sent message</h2>
                  </div>
                  <div class="card-body">
                    <form method="POST" action="{{ route('whatsapp.post') }}">
                
                        {{ csrf_field() }}
  
                        @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
                    
                        <div class="mb-3">
                            <label class="form-label" for="inputName">Phone:</label>
                            <input 
                                type="text" 
                                name="phone" 
                                id="inputName"
                                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 class="form-label" for="inputName">Message:</label>
                            <textarea 
                                name="message" 
                                id="inputName"
                                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 class="btn btn-success btn-submit">Send Message</button>
                        </div>
                    </form>
                  </div>
                </div>
                  
            </div>
        </div>
      
    </div>
</body>
</html>

Command:

php artisan serve

Conclusion:

Sending WhatsApp messages from Laravel is a powerful way to automate and improve user communication. By integrating Twilio or similar APIs, you can send secure, real-time messages effortlessly.

Start small with sandbox testing, and scale as your business grows!

Need help setting it up? MageComp offers Laravel development and WhatsApp API integration services to help you go live faster and hassle-free.

Laravel Development Services

FAQ

  1. Can I use WhatsApp API for free?

Twilio does have a WhatsApp sandbox for free development and testing. However, after you go to production, you will have to apply for WhatsApp Business API access and you will probably have to pay sfee per message sent.

  1. What are the steps to send a WhatsApp message in Laravel?

Step 1: Install Laravel

Step 2: Set up a Twilio Account

Step 3: Install twilio/sdk Package

Step 4: Create route

Step 5: Create Controller

Step 6: Create Blade File

For more details, check our blog – https://magecomp.com/blog/send-whatsapp-messages-laravel/ 

  1. Is it possible to schedule WhatsApp messages in Laravel? 

Yes, you can schedule WhatsApp messages in Laravel using Laravel’s task scheduler or queue system.

Previous Article

How to Implement Stack Navigation in a React Native App?

Next Article

How to Choose the Best Adobe Commerce Development Company?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨