In today's interconnected world, the integration of web applications with popular messaging platforms like WhatsApp has become increasingly essential. Leveraging Laravel, a powerful PHP framework, can streamline this process, enabling you to send data from a webpage directly to WhatsApp. This blog will walk you through the necessary steps to achieve this integration.
Here I am taking the example of the posts you can customize this code according to your requiredment
public function post(Request $request)
{
$post= Post::whereSlug($request->slug)->firstOrFail();
return view('frontend.post',compact('post'));
}
Here I have featched the post details on the basis of the requested slug on the blade post which is on the frontend
<script>
function cleanPhoneNumber(phoneNumber) {
// Remove spaces and plus sign using regular expressions
return phoneNumber.replace(/\s+/g, '').replace(/\+/g, '');
}
function sendWhatsAppMessage() {
const originalPhoneNumber = "{!! $setting->phone !!}"; // Get the original phone number
const cleanedPhoneNumber = cleanPhoneNumber(originalPhoneNumber); // Clean the phone number
const currentPageURL = "Link: " + window.location.href + "\n\n";
const message = "Hello, \nI would like to know more about {!! $setting->bname !!}\n\n";
const msg = "Thanks";
const fullMessage = `${message}${currentPageURL}${msg}`;
const encodedMessage = encodeURIComponent(fullMessage);
const url = `https://api.whatsapp.com/send?phone=${cleanedPhoneNumber}&text=${encodedMessage}`;
window.open(url);
}
</script>
Here I have stored the phone number in the variable phonenum and I am also sending the current full url so the admin can get the proper details that from which post this request has been arrived. Now we have passed the required message in the message variable and then we have passed all in the fullmessage variable at last I passed the url in the url variable for the whatsapp where in phone number I have passed the phone variable and in message I have passed the encoded message.
<a href="javascript:void(0)" onclick="sendWhatsAppMessage()" class="btn btn-primary btn-sm me-2"><i class="fab fa-whatsapp"></i> WhatsApp</a>
This is handle the request onclick of the button by using the onclick parameter means when this button will be clicked by the user the button will call the javascript function sendWhatsAppMessage() to send the message on the whatsapp