Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Re Captcha Validator Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel

Since this package is Symfony-focused, Laravel integration requires a few adjustments. Start by installing via Composer:

composer require dario_swain/re-captcha-validator

First Use Case: Adding reCAPTCHA to a Form

  1. Configure Google reCAPTCHA Keys Add your public/private keys to .env:

    RECAPTCHA_PUBLIC_KEY=your_public_key
    RECAPTCHA_PRIVATE_KEY=your_private_key
    
  2. Register the Service Provider In config/app.php, add the package's service provider (adapted for Laravel):

    'providers' => [
        // ...
        DarioSwain\ReCaptchaValidator\ReCaptchaServiceProvider::class,
    ],
    
  3. Publish Configuration (Optional) Publish the package's config:

    php artisan vendor:publish --provider="DarioSwain\ReCaptchaValidator\ReCaptchaServiceProvider"
    
  4. 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')
                )
            ],
        ];
    }
    
  5. 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>
    

Implementation Patterns

Workflow: Form Submission with reCAPTCHA

  1. 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>
    
  2. 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.');
        }
    }
    
  3. 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
            ]);
        }
    }
    

Integration Tips

  • 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');
    });
    

Gotchas and Tips

Pitfalls

  1. 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).

  2. 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
        ];
    }
    
  3. 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.

  4. 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.

Debugging

  • 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'));
    

Tips

  1. 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
    
  2. 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.',
        ];
    }
    
  3. 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;
        }
    }
    
  4. 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);
    });
    
  5. 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>
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky