How to Implement Google reCAPTCHA in Laravel to Prevent Bot Spam.
🚀 Why You Need reCAPTCHA in Laravel?
Bots often target web forms such as login, registration, or contact forms to send spam or perform brute-force attacks. Google reCAPTCHA is a powerful tool that helps distinguish between human users and automated bots, keeping your Laravel application safe.
🔑 Step 1: Get Google reCAPTCHA API Keys :-
- Go to Google reCAPTCHA Admin Console.
- Login with your google account.
- Go in the Guide menu and click on Get Started button.
- Register your site and choose reCAPTCHA v3.
- Copy the Site Key and Secret Key.
- Submit changes.
Load below js API :
<script src="https://www.google.com/recaptcha/api.js"></script>
Add a callback function to handle the token.
<script> function onSubmit(token) { document.getElementById("demo-form").submit(); } </script>
Add attributes to your html button.
<button class="g-recaptcha" data-sitekey="reCAPTCHA_site_key" data-callback='onSubmit' data-action='submit'>Submit</button>
Now Create rule for captcha with artisan command
php artisan make:rule captchaRule
Write rule in the captchaRule.php
$response = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
'secret' => env('GOOGLE_RECAPTCHA_SECRET'),
'response' => $value,
'remoteip' => request()->ip(),
])->json();
if (!isset($response['success']) || $response['success'] !== true) {
$fail('The reCAPTCHA verification failed. Please try again.');
}
Now you need to add validation in controller for captcha
use App\Rules\ReCaptcha;
$validator = Validator::make($request->all(), [
'g-recaptcha-response' => [new ReCaptcha]
]);
Show the error message
@error('g-recaptcha-response')
<span class="text-danger ms-2 mb-3">{{ $message }}</span>
@enderror
🎯 Conclusion
By integrating Google reCAPTCHA in your Laravel forms, you can prevent bot spam and keep your application secure. This simple yet powerful feature ensures that only genuine users can submit your forms.