If you prefer not to use a package, you can manually integrate Google reCAPTCHA into your Laravel application. Below are the steps:
.env
In your .env
file, add the following:
RECAPTCHA_SITE_KEY=your-site-key RECAPTCHA_SECRET_KEY=your-secret-key
Replace your-site-key
and your-secret-key
with the values from the Google reCAPTCHA admin console.
In your Blade file where you want to include the reCAPTCHA widget, add the following:
<form method="POST" action="{{ route('your.route.name') }}"> @csrf <!-- Your form inputs here --> <div class="g-recaptcha" data-sitekey="{{ env('RECAPTCHA_SITE_KEY') }}"></div> <button type="submit">Submit</button> </form> <script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://www.google.com/recaptcha/api.js?render={{ env('RECAPTCHA_SITE_KEY') }}"></script> <form method="POST" action="{{ route('your.route.name') }}" id="your-form-id"> @csrf <!-- Your form inputs here --> <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response"> <button type="submit">Submit</button> </form> <script> grecaptcha.ready(function() { grecaptcha.execute('{{ env('RECAPTCHA_SITE_KEY') }}', { action: 'submit' }).then(function(token) { document.getElementById('g-recaptcha-response').value = token; }); }); </script>
In your Controller, verify the reCAPTCHA response:
use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; public function yourFormHandler(Request $request) { $recaptchaResponse = $request->input('g-recaptcha-response'); $secretKey = env('RECAPTCHA_SECRET_KEY'); // Verify reCAPTCHA response $response = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [ 'secret' => $secretKey, 'response' => $recaptchaResponse, 'remoteip' => $request->ip(), ]); $responseData = $response->json(); if (!$responseData['success'] || $responseData['score'] < 0.5) { // Adjust 'score' threshold for v3 return back()->withErrors(['captcha' => 'Captcha verification failed. Please try again.']); } // Proceed with form handling logic // ... }
In your Blade file, display validation errors:
@if ($errors->has('captcha')) <div class="alert alert-danger">{{ $errors->first('captcha') }}</div> @endif
success
key in the response is sufficient.score
indicates the likelihood of the request being human. You can adjust the threshold (e.g., 0.5
).This approach does not rely on any external Laravel packages and uses only Google’s reCAPTCHA API.