Laravel - Google Recaptcha v3
Home / Snippets / PHP / Laravel - Google Recaptcha v3
Implementing Google reCAPTCHA v3 in Laravel helps protect your forms against bots without interrupting the user experience. Unlike v2, which requires clicking checkboxes, reCAPTCHA v3 assigns a score based on user behavior. In this post, we’ll create a custom Laravel validator to verify that score server-side and ensure only legitimate submissions are accepted.
First, register a custom validation rule inside your AppServiceProvider:
<?php
namespace App\Providers;
/* ... imports ... */
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
/* .... */
Validator::extend('v3Recaptcha', function ($attribute, $value, $parameters, $validator) {
$response = Http::withoutVerifying()->asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
'secret' => '*****your**secret**here*****',
'response' => $value,
'remoteip' => Request::ip()
]);
if ($response->successful()) {
$result = $response->json();
return $result['success'] && $result['score'] >= 0.5;
}
return false;
});
Validator::replacer('v3Recaptcha', function ($message, $attribute, $rule, $parameters) {
return "Recaptcha is invalid.";
});
}
}
Next, apply the new validation rule inside your form handler:
// ...
public function subscribe(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|max:150',
'email' => 'required|email',
'phone' => 'required|string',
'recaptcha' => 'required|v3Recaptcha'
]);
// ...
}
Finally, include the reCAPTCHA v3 script in your Blade template
<form>
<input type="hidden" name="recaptcha">
</form>
<script src="https://www.google.com/recaptcha/api.js?render=*****google-public-key*****"></script>
With these steps, Laravel will validate the token server-side, check the Google score, and reject suspicious requests without showing captchas to real users.