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

No Captcha Laravel Package

anhskohbo/no-captcha

Laravel package to integrate Google reCAPTCHA (No CAPTCHA) in your forms. Includes config via .env, Blade helpers to render JS and display widgets, supports language and custom attributes, and works with Laravel 5+ (auto-discovery on 5.5+).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require anhskohbo/no-captcha
    

    (Auto-discovery enabled for Laravel 5.5+; otherwise, register the service provider and facade in config/app.php.)

  2. Configuration: Add to .env:

    NOCAPTCHA_SECRET=your_secret_key
    NOCAPTCHA_SITEKEY=your_site_key
    

    (Obtain keys from Google reCAPTCHA Admin.)

  3. Publish Config (if not using auto-discovery):

    php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"
    
  4. First Use Case: Add reCAPTCHA to a form in Blade:

    {!! NoCaptcha::renderJs() !!}
    {!! NoCaptcha::display() !!}
    

    Validate the response in a controller:

    $validator = Validator::make(request()->all(), [
        'g-recaptcha-response' => 'required|captcha',
    ]);
    

Implementation Patterns

Usage Patterns

1. Standard reCAPTCHA Flow

  • Blade Integration:
    <!-- Load JS (once per page) -->
    {!! NoCaptcha::renderJs('en', false, 'onloadCallback') !!}
    
    <!-- Display widget -->
    {!! NoCaptcha::display(['data-theme' => 'light', 'data-size' => 'compact']) !!}
    
  • Validation:
    $rules = ['g-recaptcha-response' => 'required|captcha'];
    $validator = Validator::make($request->all(), $rules);
    

2. Invisible reCAPTCHA (Submit Button)

  • Blade Integration:

    {!! NoCaptcha::displaySubmit('contact-form', 'Submit', ['data-theme' => 'dark']) !!}
    

    (Requires id="contact-form" on the form.)

  • Validation: Same as standard flow; the package auto-triggers validation on form submission.

3. Multi-Language Support

  • Pass language code to renderJs():
    {!! NoCaptcha::renderJs('fr') !!}
    

4. Custom Validation Messages

  • Add to resources/lang/en/validation.php:
    'custom' => [
        'g-recaptcha-response' => [
            'required' => 'Veuillez prouver que vous n\'êtes pas un robot.',
            'captcha' => 'Erreur de vérification. Réessayez ou contactez l\'admin.',
        ],
    ],
    

5. Testing

  • Unit Tests:
    NoCaptcha::shouldReceive('verifyResponse')->andReturn(true);
    
  • HTTP Tests:
    $response = $this->post('/register', [
        'g-recaptcha-response' => '1', // Mock response
        'email' => 'test@example.com',
    ]);
    

Workflows

Form Submission Workflow

  1. Render JS (once per page, typically in layout).
  2. Display Widget in the form.
  3. Validate g-recaptcha-response in the controller.
  4. Handle Errors (e.g., show validation messages).

Invisible reCAPTCHA Workflow

  1. Display Submit Button with displaySubmit().
  2. Auto-Validation: The package triggers validation on form submission (no manual check needed).
  3. Error Handling: Ensure the form ID matches the displaySubmit() argument.

Integration Tips

  • Laravel 5.5+: Skip manual service provider/facade registration (auto-discovery).
  • Lumen: Use the standalone NoCaptcha class or manually register the service provider.
  • Frontend Frameworks: For Vue/React, load the JS globally and use the data-sitekey attribute manually:
    <div class="g-recaptcha" data-sitekey="{{ config('services.nocaptcha.sitekey') }}"></div>
    
  • Dynamic Site Keys: Override config('services.nocaptcha.sitekey') per environment or feature flag.
  • Caching: ReCAPTCHA responses are short-lived; avoid caching validated forms.

Gotchas and Tips

Pitfalls

  1. Missing JS Rendering:

    • Error: reCAPTCHA widget fails to load.
    • Fix: Ensure NoCaptcha::renderJs() is called before NoCaptcha::display() in the Blade template.
    • Debug: Check browser console for grecaptcha errors (e.g., missing API key).
  2. Form ID Mismatch (Invisible reCAPTCHA):

    • Error: Silent form submission failure.
    • Fix: Verify the form id matches the first argument in displaySubmit('form-id', ...).
    • Debug: Inspect the generated HTML for data-formid attributes.
  3. Validation Field Name Hardcoding:

    • Issue: The package expects g-recaptcha-response; custom field names require middleware:
      $request->merge(['g-recaptcha-response' => $request->input('custom_captcha_field')]);
      
    • Workaround: Use a middleware to rename inputs before validation.
  4. Testing Pitfalls:

    • Issue: Tests fail due to missing g-recaptcha-response in HTTP requests.
    • Fix: Include the field in test requests:
      $this->post('/register', ['g-recaptcha-response' => '1', ...]);
      
    • Mocking: For unit tests, mock both verifyResponse and display:
      NoCaptcha::shouldReceive('verifyResponse')->andReturn(true);
      NoCaptcha::shouldReceive('display')->andReturn('<input type="hidden" name="g-recaptcha-response" value="1" />');
      
  5. Secret Key Exposure:

    • Risk: .env keys may be committed accidentally.
    • Fix: Add .env to .gitignore and use php artisan config:clear after key changes.
  6. Invisible reCAPTCHA Edge Cases:

    • Issue: Form submission fails if the JS callback isn’t triggered.
    • Fix: Ensure the form’s onsubmit or data-callback attributes align with the package’s expectations.

Debugging

  • reCAPTCHA Errors:

    • Check Google’s reCAPTCHA Debugging Guide.
    • Enable debug mode in .env:
      NOCAPTCHA_DEBUG=true
      
    • Log responses to verify:
      $response = NoCaptcha::verifyResponse($request->input('g-recaptcha-response'));
      \Log::debug('reCAPTCHA Response', ['success' => $response, 'input' => $request->input('g-recaptcha-response')]);
      
  • Validation Errors:

    • Ensure the captcha rule is correctly applied:
      $validator = Validator::make($request->all(), [
          'g-recaptcha-response' => 'required|captcha',
      ]);
      
    • Check for typos in field names or validation messages.

Config Quirks

  • Auto-Discovery:

    • Laravel 5.5+ skips manual registration, but ensure the package is listed in composer.json.
    • For custom configurations, publish the config file:
      php artisan vendor:publish --tag="nocaptcha-config"
      
  • Language Fallback:

    • The package defaults to en. Override in renderJs():
      {!! NoCaptcha::renderJs('fr') !!}
      
  • Invisible reCAPTCHA:

    • Requires a form ID and a submit button. The package auto-generates a callback, but ensure no conflicting JS exists.

Extension Points

  1. Custom Validation Logic:

    • Extend the captcha rule by creating a custom validator:
      use Anhskohbo\NoCaptcha\Rules\Recaptcha;
      
      $rules = ['g-recaptcha-response' => [new Recaptcha]];
      
  2. Middleware for Dynamic Keys:

    • Override site/secret keys per request:
      app('nocaptcha')->setSiteKey('dynamic-key-' . $user->id);
      
  3. Event Listeners:

    • Listen for reCAPTCHA verification events (e.g., log failed attempts):
      NoCaptcha::failed(function ($response) {
          \Log::warning('reCAPTCHA failed', ['response' => $response]);
      });
      
  4. Alternative CAPTCHA Providers:

    • Replace the verifyResponse method by extending the NoCaptcha class:
      class CustomNoCaptcha extends \Anhskohbo\NoCaptcha\NoCaptcha {
          public
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport