dario_swain/re-captcha-validator
Lightweight Google reCAPTCHA v2 form type and validator component for Symfony2. Not a bundle—fully configurable services. Install via Composer, set public/private keys, and register the ReCaptcha form type to validate submissions in your forms.
Since this package is Symfony-focused, Laravel integration requires a few adjustments. Start by installing via Composer:
composer require dario_swain/re-captcha-validator
Configure Google reCAPTCHA Keys
Add your public/private keys to .env:
RECAPTCHA_PUBLIC_KEY=your_public_key
RECAPTCHA_PRIVATE_KEY=your_private_key
Register the Service Provider
In config/app.php, add the package's service provider (adapted for Laravel):
'providers' => [
// ...
DarioSwain\ReCaptchaValidator\ReCaptchaServiceProvider::class,
],
Publish Configuration (Optional) Publish the package's config:
php artisan vendor:publish --provider="DarioSwain\ReCaptchaValidator\ReCaptchaServiceProvider"
Use in a Form Request
Extend Illuminate\Foundation\Http\FormRequest and add the reCAPTCHA validation rule:
use DarioSwain\ReCaptchaValidator\Validator\ReCaptchaValidator;
public function rules()
{
return [
'g-recaptcha-response' => [
new ReCaptchaValidator(
config('services.recaptcha.public_key'),
config('services.recaptcha.private_key')
)
],
];
}
Add reCAPTCHA to a Blade Form Include the reCAPTCHA script in your layout:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
Add the reCAPTCHA field to your form:
<div class="g-recaptcha" data-sitekey="{{ config('services.recaptcha.public_key') }}"></div>
Frontend Integration Use the Google reCAPTCHA script and render the widget in your Blade template:
<div class="g-recaptcha"
data-sitekey="{{ config('services.recaptcha.public_key') }}"
data-callback="onSubmit"
data-size="invisible">
</div>
Backend Validation
Validate the g-recaptcha-response token in your FormRequest:
public function validateReCaptcha($attribute, $value, $fail)
{
$validator = new ReCaptchaValidator(
config('services.recaptcha.public_key'),
config('services.recaptcha.private_key')
);
if (!$validator->isValid($value)) {
$fail('reCAPTCHA verification failed.');
}
}
Customizing the Form Type (Advanced)
If you need to extend the ReCaptchaType, create a custom form type in Laravel:
use DarioSwain\ReCaptchaValidator\Form\ReCaptchaType;
use Symfony\Component\Form\AbstractType;
class CustomReCaptchaType extends AbstractType
{
public function getParent()
{
return ReCaptchaType::class;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'allow_extra_fields' => true,
'theme' => 'light', // Customize theme
]);
}
}
Laravel Form Builder Compatibility
Use the package's validator directly with Laravel's Validator facade:
use DarioSwain\ReCaptchaValidator\Validator\ReCaptchaValidator;
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'g-recaptcha-response' => [
new ReCaptchaValidator(
config('services.recaptcha.public_key'),
config('services.recaptcha.private_key')
)
],
]);
Testing Disable reCAPTCHA validation in tests by mocking the validator:
$validator = $this->createMock(ReCaptchaValidator::class);
$validator->method('isValid')->willReturn(true);
$this->app->instance(ReCaptchaValidator::class, $validator);
Dynamic Keys Fetch keys from a database or API if needed:
$publicKey = Cache::remember('recaptcha_public_key', 3600, function () {
return Setting::where('key', 'recaptcha_public_key')->value('value');
});
Deprecated Symfony Components
The package relies on Symfony's Form and Validator components, which may cause compatibility issues in newer Laravel versions. Ensure you’re using a compatible version (e.g., Symfony 2.x components).
Missing allow_extra_fields
Forgetting to set allow_extra_fields: true in your form configuration will cause the g-recaptcha-response field to be ignored:
// Laravel FormRequest example
public function rules()
{
return [
'g-recaptcha-response' => 'required|recaptcha', // Custom rule
];
}
CORS Issues with API Requests
If using the reCAPTCHA API directly, ensure your server allows requests to https://www.google.com/recaptcha/api/siteverify. Laravel’s Http client may need CORS headers configured.
Outdated Package The last release was in 2016, so some features (e.g., reCAPTCHA v3) are unsupported. Use at your own risk or fork the package.
Validation Failures Check the raw response from Google’s API by logging the validator’s output:
$validator = new ReCaptchaValidator($publicKey, $privateKey);
$response = $validator->verify($token);
\Log::info($response); // Debug the API response
Token Mismatch
Ensure the g-recaptcha-response token is being submitted with the form. Inspect the request payload:
\Log::info($request->input('g-recaptcha-response'));
Environment-Specific Keys
Use Laravel’s .env files to manage keys per environment:
RECAPTCHA_PUBLIC_KEY_local=local_key
RECAPTCHA_PRIVATE_KEY_production=prod_key
Custom Error Messages
Override the default error message in your FormRequest:
public function messages()
{
return [
'g-recaptcha-response.recaptcha' => 'Please complete the CAPTCHA to proceed.',
];
}
Extend the Validator Create a custom validator for additional logic (e.g., IP-based checks):
use DarioSwain\ReCaptchaValidator\Validator\ReCaptchaValidator;
class CustomReCaptchaValidator extends ReCaptchaValidator
{
public function isValid($response)
{
if (!$this->verify($response)) {
return false;
}
// Add custom logic (e.g., rate limiting)
return true;
}
}
Cache API Responses Reduce API calls by caching the reCAPTCHA verification response:
$response = Cache::remember("recaptcha_{$token}", 300, function () use ($validator, $token) {
return $validator->verify($token);
});
Fallback for JavaScript Disabled Provide a hidden field fallback for users without JavaScript:
<input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
<script>
document.getElementById('g-recaptcha-response').value = grecaptcha.getResponse();
</script>
How can I help you explore Laravel packages today?