PHP code example of izzuddinmohsin / laravel-whatsapp

1. Go to this page and download the library: Download izzuddinmohsin/laravel-whatsapp library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

izzuddinmohsin / laravel-whatsapp example snippets


use IzzuddinMohsin\LaravelWhatsApp\Facades\WhatsApp;

// Text message
WhatsApp::to('60123456789')->text('Hello from Laravel!');

// Image with caption
WhatsApp::to('60123456789')->image('https://example.com/photo.jpg', 'Check this out!');

// Document
WhatsApp::to('60123456789')->document('https://example.com/invoice.pdf', 'invoice.pdf', 'Your invoice');

// Audio
WhatsApp::to('60123456789')->audio('https://example.com/audio.mp3');

// Video
WhatsApp::to('60123456789')->video('https://example.com/video.mp4', 'Watch this');

// Location
WhatsApp::to('60123456789')->location(3.1390, 101.6869, 'KL Tower', 'Kuala Lumpur');

// Contact card
WhatsApp::to('60123456789')->contact('Ali Ahmad', '60198765432', 'Syarikat ABC');

// Buttons
WhatsApp::to('60123456789')->buttons(
    title: 'Choose an option',
    description: 'What would you like to do?',
    buttons: [
        ['id' => 'order', 'text' => 'Track Order'],
        ['id' => 'support', 'text' => 'Get Support'],
        ['id' => 'info', 'text' => 'More Info'],
    ]
);

// List message
WhatsApp::to('60123456789')->list(
    title: 'Our Menu',
    description: 'Choose from our selections',
    buttonText: 'View Menu',
    sections: [
        [
            'title' => 'Drinks',
            'rows' => [
                ['title' => 'Teh Tarik', 'description' => 'RM 3.00', 'rowId' => 'teh_tarik'],
                ['title' => 'Kopi O', 'description' => 'RM 2.50', 'rowId' => 'kopi_o'],
            ],
        ],
    ]
);

// Check connection status
$info = WhatsApp::instanceInfo();
echo $info->status;        // 'open', 'close', etc.
echo $info->phoneNumber;
echo $info->isConnected(); // true/false

// Get QR code for pairing
$qrCode = WhatsApp::qrCode(); // base64 image

// Check if number exists on WhatsApp
$exists = WhatsApp::isOnWhatsApp('60123456789'); // true/false

// Logout
WhatsApp::logout();

// Create a new instance on Evolution API
WhatsApp::createInstance([
    'name' => 'marketing',
    'reject_call' => true,
    'msg_call' => 'Sorry, we cannot take calls.',
    'groups_ignore' => true,
    'always_online' => true,
    'read_messages' => true,
]);

// Delete instance
WhatsApp::instance('marketing')->deleteInstance();

// Restart instance
WhatsApp::instance('marketing')->restartInstance();

// Fetch all instances from Evolution API
$instances = WhatsApp::fetchInstances();

// Get connected instances from database
$connected = WhatsApp::getConnectedInstances();

// Set webhook URL for current instance
WhatsApp::setWebhook('https://your-app.com/whatsapp/webhook');

// Set with specific events
WhatsApp::setWebhook('https://your-app.com/whatsapp/webhook', [
    'MESSAGES_UPSERT',
    'MESSAGES_UPDATE',
    'CONNECTION_UPDATE',
]);

// Get current webhook configuration
$config = WhatsApp::getWebhook();

// Get profile picture
$url = WhatsApp::getProfilePicture('60123456789');

// Fetch messages from a chat
$messages = WhatsApp::fetchMessages('[email protected]', 50);

// Update instance settings
WhatsApp::updateSettings([
    'rejectCall' => true,
    'alwaysOnline' => true,
]);

// Switch instance at runtime
WhatsApp::instance('marketing')->to('60123456789')->text('Promo!');
WhatsApp::instance('support')->to('60123456789')->text('Ticket resolved');

// Each call is immutable — won't affect other calls
$marketing = WhatsApp::instance('marketing');
$support = WhatsApp::instance('support');

$marketing->to('60123456789')->text('From marketing');
$support->to('60123456789')->text('From support');

WhatsApp::setWebhook('https://your-app.com/whatsapp/webhook');

// app/Listeners/HandleWhatsAppMessage.php
namespace App\Listeners;

use IzzuddinMohsin\LaravelWhatsApp\Events\WhatsAppMessageReceived;
use IzzuddinMohsin\LaravelWhatsApp\Facades\WhatsApp;

class HandleWhatsAppMessage
{
    public function handle(WhatsAppMessageReceived $event): void
    {
        $message = $event->message;

        // Access message properties
        echo $message->from;        // '60123456789'
        echo $message->text;        // 'Hello!'
        echo $message->type;        // 'conversation', 'imageMessage', etc.
        echo $message->pushName;    // Sender's name
        echo $message->isGroup;     // true/false
        echo $message->isText();    // true/false
        echo $message->isMedia();   // true/false

        // Auto-reply example
        if ($message->isText() && str_contains(strtolower($message->text), 'hello')) {
            WhatsApp::to($message->from)->text("Hi {$message->pushName}!");
        }
    }
}

// app/Providers/EventServiceProvider.php (Laravel 10)
// or bootstrap/app.php (Laravel 11+)

use IzzuddinMohsin\LaravelWhatsApp\Events\WhatsAppMessageReceived;
use IzzuddinMohsin\LaravelWhatsApp\Events\WhatsAppMessageStatusUpdated;
use IzzuddinMohsin\LaravelWhatsApp\Events\WhatsAppConnectionStatusChanged;
use IzzuddinMohsin\LaravelWhatsApp\Events\InstanceConnected;
use IzzuddinMohsin\LaravelWhatsApp\Events\InstanceDisconnected;
use IzzuddinMohsin\LaravelWhatsApp\Events\QrCodeUpdated;

// Laravel 11+
Event::listen(WhatsAppMessageReceived::class, HandleWhatsAppMessage::class);
Event::listen(WhatsAppMessageStatusUpdated::class, HandleStatusUpdate::class);
Event::listen(WhatsAppConnectionStatusChanged::class, HandleConnectionChange::class);
Event::listen(InstanceConnected::class, HandleInstanceConnected::class);
Event::listen(InstanceDisconnected::class, HandleInstanceDisconnected::class);
Event::listen(QrCodeUpdated::class, HandleQrCodeUpdated::class);

use IzzuddinMohsin\LaravelWhatsApp\Concerns\CanSendWhatsappMessage;

class OrderService
{
    use CanSendWhatsappMessage;

    public function notifyCustomer(Order $order): void
    {
        $this->sendWhatsappText(
            to: $order->customer_phone,
            message: "Your order #{$order->id} is ready!",
        );

        $this->sendWhatsappDocument(
            to: $order->customer_phone,
            url: $order->invoice_url,
            filename: "invoice-{$order->id}.pdf",
            caption: 'Here is your invoice',
        );
    }

    public function sendPromo(): void
    {
        // Send via specific instance
        $this->sendWhatsappImage(
            to: '60123456789',
            url: 'https://example.com/promo.jpg',
            caption: 'Special offer!',
            instanceName: 'marketing',
        );
    }
}

// app/Notifications/OrderShipped.php
namespace App\Notifications;

use Illuminate\Notifications\Notification;
use IzzuddinMohsin\LaravelWhatsApp\Notifications\WhatsAppChannel;
use IzzuddinMohsin\LaravelWhatsApp\Notifications\WhatsAppMessage;

class OrderShipped extends Notification
{
    public function via($notifiable): array
    {
        return [WhatsAppChannel::class];
    }

    public function toWhatsApp($notifiable): WhatsAppMessage
    {
        return WhatsAppMessage::create()
            ->text("Hi {$notifiable->name}! Your order #{$this->order->id} has been shipped!");
    }
}

// Text
WhatsAppMessage::create()->text('Hello!');

// Image
WhatsAppMessage::create()->image('https://example.com/photo.jpg', 'Caption');

// Video
WhatsAppMessage::create()->video('https://example.com/video.mp4', 'Caption');

// Audio
WhatsAppMessage::create()->audio('https://example.com/audio.mp3');

// Document
WhatsAppMessage::create()->document('https://example.com/file.pdf', 'file.pdf', 'Your document');

// Location
WhatsAppMessage::create()->location(3.1390, 101.6869, 'KL Tower', 'Kuala Lumpur');

// Contact
WhatsAppMessage::create()->contact('Ali Ahmad', '60198765432', 'Syarikat ABC');

// app/Models/User.php
public function routeNotificationForWhatsapp(): ?string
{
    return $this->phone_number; // e.g., '60123456789'
}

$user->notify(new OrderShipped($order));

// Laravel 11+
Schedule::command('whatsapp:cleanup')->daily();

use IzzuddinMohsin\LaravelWhatsApp\Enums\MessageTypeEnum;
use IzzuddinMohsin\LaravelWhatsApp\Enums\MessageStatusEnum;
use IzzuddinMohsin\LaravelWhatsApp\Enums\MessageDirectionEnum;
use IzzuddinMohsin\LaravelWhatsApp\Enums\ConnectionStatusEnum;

// Message types
MessageTypeEnum::TEXT;      // 'text'
MessageTypeEnum::IMAGE;     // 'image'
MessageTypeEnum::VIDEO;     // 'video'
MessageTypeEnum::AUDIO;     // 'audio'
MessageTypeEnum::DOCUMENT;  // 'document'
MessageTypeEnum::LOCATION;  // 'location'
MessageTypeEnum::CONTACT;   // 'contact'

// Message statuses
MessageStatusEnum::PENDING;   // 'pending'
MessageStatusEnum::SENT;      // 'sent'
MessageStatusEnum::DELIVERED;  // 'delivered'
MessageStatusEnum::READ;      // 'read'
MessageStatusEnum::FAILED;    // 'failed'

// Directions
MessageDirectionEnum::INCOMING;  // 'incoming'
MessageDirectionEnum::OUTGOING;  // 'outgoing'

// Connection status
ConnectionStatusEnum::OPEN;        // 'open'
ConnectionStatusEnum::CLOSE;       // 'close'
ConnectionStatusEnum::CONNECTING;  // 'connecting'

use IzzuddinMohsin\LaravelWhatsApp\Models\WhatsappInstance;
use IzzuddinMohsin\LaravelWhatsApp\Models\WhatsappMessage;
use IzzuddinMohsin\LaravelWhatsApp\Models\WhatsappWebhook;

// Instances
$instance = WhatsappInstance::where('name', 'default')->first();
$instance->isConnected();    // true/false
$instance->messages;         // HasMany relationship
$instance->webhooks;         // HasMany relationship

// Messages
$messages = WhatsappMessage::where('phone', '60123456789')
    ->where('direction', 'incoming')
    ->latest()
    ->get();

// Update message status
$message->markAsSent();
$message->markAsDelivered();
$message->markAsRead();

// Webhooks
$pending = WhatsappWebhook::pending()->get();
$failed = WhatsappWebhook::failed()->get();
$messageEvents = WhatsappWebhook::byEvent('messages.upsert')->get();

use IzzuddinMohsin\LaravelWhatsApp\Exceptions\WhatsAppException;

try {
    WhatsApp::to('60123456789')->text('Hello!');
} catch (WhatsAppException $e) {
    Log::error('WhatsApp send failed: ' . $e->getMessage());
}
bash
php artisan vendor:publish --tag=whatsapp-config
bash
php artisan vendor:publish --tag=whatsapp-migrations
php artisan migrate
bash
php artisan queue:work --queue=whatsapp
bash
# Use config defaults (30 days webhooks, 90 days messages)
php artisan whatsapp:cleanup

# Custom retention
php artisan whatsapp:cleanup --webhooks-days=7 --messages-days=30

# Preview what would be deleted
php artisan whatsapp:cleanup --dry-run