Skip to content

Instantly share code, notes, and snippets.

@Lelectrolux
Created November 18, 2025 16:40
Show Gist options
  • Select an option

  • Save Lelectrolux/b782c9eb41d8c49de5b79fe953946f7f to your computer and use it in GitHub Desktop.

Select an option

Save Lelectrolux/b782c9eb41d8c49de5b79fe953946f7f to your computer and use it in GitHub Desktop.
Laravel Rule for Google Recaptcha v3
<?php
declare(strict_types=1);
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* @link https://developers.google.com/recaptcha/docs/v3
*/
class RecaptchaRule implements ValidationRule
{
public bool $implicit = true;
public function __construct(
private string $hostname,
private string $action,
private ?string $ip,
) {}
/**
* Run the validation rule.
*
* @param Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (config('services.recaptcha.disabled')) {
return;
}
if (empty($value)) {
$fail(__('validation.recaptcha'));
return;
}
try {
$response = Http::createPendingRequest()
->asForm()
->post(
'https://www.google.com/recaptcha/api/siteverify',
[
'secret' => config('services.recaptcha.secret_key'),
'response' => $value,
'remoteip' => $this->ip,
]
);
$response->throwUnlessStatus(200);
if ($response->json('success') !== true
|| $response->json('hostname') !== $this->hostname
|| $response->json('action') !== $this->action
|| $response->json('score') <= config('services.recaptcha.threshold')
) {
$fail(__('validation.recaptcha'));
}
} catch (Throwable $e) {
report($e);
$fail(__('validation.recaptcha'));
}
}
}
<?php
declare(strict_types=1);
return [
//...
'recaptcha' => [
'site_key' => env('RECAPTCHA_SITE_KEY'),
'secret_key' => env('RECAPTCHA_SECRET_KEY'),
'threshold' => env('RECAPTCHA_THRESHOLD', 0.5),
'disabled' => (bool) env('RECAPTCHA_DISABLED', false),
],
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment