composer create-project --prefer-dist laravel/laravel-twillo
cd laravel-twillo
composer require twilio/sdk
TWILIO_SID=your_twilio_sid
TWILIO_AUTH_TOKEN=your_twilio_auth_token
TWILIO_FROM=your_twilio_phone_number
php artisan make:controller WhatsAppController
<?php
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'));
$twilio->messages
->create("whatsapp:$to",
[
"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');
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Send WhatsApp Message</title>
</head>
<body>
<h1>Send WhatsApp Message</h1>
@if (session('success'))
<p style="color: green;">{{ session('success') }}</p>
@endif
<form action="{{ route('whatsapp.send') }}" method="post">
@csrf
<label for="to">To (WhatsApp Phone Number):</label>
<input type="text" name="to" required>
<br>
<label for="message">Message:</label>
<textarea name="message" required></textarea>
<br>
<button type="submit">Send WhatsApp Message</button>
</form>
</body>
</html>
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');
php artisan serve
Subscribe to the Email Newsletter