Installation
composer require bghanem/recaptcha-bundle
Add to config/app.php under providers:
Bghanem\RecaptchaBundle\RecaptchaServiceProvider::class,
Publish config (optional):
php artisan vendor:publish --provider="Bghanem\RecaptchaBundle\RecaptchaServiceProvider"
Configuration
Edit .env or config/recaptcha.php:
RECAPTCHA_SITE_KEY=your_site_key
RECAPTCHA_SECRET_KEY=your_secret_key
RECAPTCHA_VERSION=v3 # or v2
First Use Case Add to a form (Blade):
@if(config('recaptcha.version') === 'v2')
{!! recaptcha_v2() !!}
@else
{!! recaptcha_v3() !!}
@endif
Validate in a controller:
use Bghanem\RecaptchaBundle\Recaptcha;
public function store(Request $request, Recaptcha $recaptcha) {
if (!$recaptcha->verify($request->input('g-recaptcha-response'))) {
return back()->withErrors(['captcha' => 'Invalid captcha']);
}
}
Form Validation
Use in FormRequest or controller:
public function rules() {
return [
'g-recaptcha-response' => 'required|captcha',
];
}
Dynamic Version Handling Switch versions via config or runtime:
$recaptcha = new Recaptcha(config('recaptcha.version'));
API Integration For non-form submissions (e.g., AJAX):
$response = $recaptcha->verify($token, ['remote_ip' => $request->ip()]);
Custom Error Messages
Override in AppServiceProvider:
Recaptcha::setErrorMessage('Invalid verification');
Laravel Nova/Forge
Extend RecaptchaServiceProvider to auto-register in Nova/Forge.
@verbatim for raw JS if custom styling is needed.Recaptcha to tenant-specific keys via a resolver.Recaptcha in PHPUnit:
$this->app->instance(Recaptcha::class, Mockery::mock(Recaptcha::class));
Version Mismatch
RECAPTCHA_VERSION matches the HTML snippet (v2 vs. v3).AppServiceProvider boot:
if (!in_array(config('recaptcha.version'), ['v2', 'v3'])) {
throw new \RuntimeException('Invalid recaptcha version');
}
Missing IP Address
remote_ip for verification. Defaults to null if omitted.$recaptcha->verify($token, ['remote_ip' => $request->ip()]);
CSRF Token Conflicts
@csrf if not namespaced.name="g-recaptcha-response" explicitly.Rate Limiting
Enable Logging
Set RECAPTCHA_DEBUG=true in .env to log verification errors.
Test Tokens
Use Google’s test keys (6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhQ) to debug locally.
Custom Verification Logic
Extend the Recaptcha class:
class CustomRecaptcha extends Recaptcha {
public function verify($token, $options = []) {
// Add custom logic (e.g., bypass for admins)
return parent::verify($token, $options);
}
}
Event Listeners
Listen for recaptcha.failed events (register in EventServiceProvider):
protected $listen = [
'recaptcha.failed' => [\App\Listeners\LogCaptchaFailures::class],
];
Dynamic Keys
Override getSiteKey()/getSecretKey() in the service provider for environment-specific keys.
recaptcha_v2()/recaptcha_v3() calls until needed (e.g., in a component).How can I help you explore Laravel packages today?