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” into your app. Provides helpers to render the JS, display normal or invisible widgets, and validate responses. Supports Laravel auto-discovery, with simple .env configuration for site key and secret.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation: Add the package via Composer:
    composer require anhskohbo/no-captcha
    
  2. Configuration: Publish the config file and set your Google reCAPTCHA keys in .env:
    NOCAPTCHA_SECRET=your_secret_key
    NOCAPTCHA_SITEKEY=your_site_key
    
    For Laravel 5.5+, auto-discovery handles the rest. For older versions, register the service provider and facade alias in config/app.php.
  3. First Use Case: Protect a form from bots by:
    • Rendering the reCAPTCHA widget in your Blade template:
      {!! NoCaptcha::renderJs() !!}
      {!! NoCaptcha::display() !!}
      
    • Validating the response in your controller:
      $validator = Validator::make(request()->all(), [
          'g-recaptcha-response' => 'required|captcha',
      ]);
      

Implementation Patterns

Workflow: Form Protection

  1. Frontend Integration:

    • Include the reCAPTCHA script and widget in your form:
      {!! NoCaptcha::renderJs('en', false, 'recaptchaCallback') !!}
      <form method="POST" action="/submit">
          <!-- Form fields -->
          {!! NoCaptcha::display(['data-theme' => 'dark']) !!}
          <button type="submit">Submit</button>
      </form>
      
    • For invisible reCAPTCHA (v3), use:
      {!! NoCaptcha::displaySubmit('form-id', 'Submit', ['data-theme' => 'dark']) !!}
      
  2. Backend Validation:

    • Validate the token in your controller or Form Request:
      public function store(StoreFormRequest $request) {
          // Validation handled by FormRequest
      }
      
      In StoreFormRequest.php:
      public function rules() {
          return [
              'g-recaptcha-response' => 'required|captcha',
          ];
      }
      
    • Customize error messages in resources/lang/en/validation.php:
      'custom' => [
          'g-recaptcha-response' => [
              'required' => 'Please verify you are not a robot.',
              'captcha' => 'CAPTCHA verification failed. Please try again.',
          ],
      ],
      
  3. API Protection:

    • Use middleware to validate reCAPTCHA tokens for API routes:
      // app/Http/Middleware/ValidateRecaptcha.php
      public function handle($request, Closure $next) {
          if ($request->is('api/*') && !$request->has('g-recaptcha-response')) {
              return response()->json(['error' => 'CAPTCHA required'], 403);
          }
          if ($request->has('g-recaptcha-response') && !NoCaptcha::verifyResponse($request->input('g-recaptcha-response'))) {
              return response()->json(['error' => 'Invalid CAPTCHA'], 403);
          }
          return $next($request);
      }
      
    • Register the middleware in app/Http/Kernel.php:
      protected $routeMiddleware = [
          'recaptcha' => \App\Http\Middleware\ValidateRecaptcha::class,
      ];
      
    • Apply to routes:
      Route::post('/api/submit', [Controller::class, 'store'])->middleware('recaptcha');
      

Dynamic Configuration

  • Per-Form Enforcement: Disable reCAPTCHA for low-risk forms by omitting validation or using conditional logic:

    $rules = [];
    if ($this->isHighRiskForm()) {
        $rules['g-recaptcha-response'] = 'required|captcha';
    }
    
  • Language Support: Localize reCAPTCHA for multilingual apps:

    {!! NoCaptcha::renderJs(app()->getLocale()) !!}
    

Testing Patterns

  • Unit Testing: Mock the facade to simulate CAPTCHA validation:
    NoCaptcha::shouldReceive('verifyResponse')
        ->once()
        ->andReturn(true);
    
  • HTTP Testing: Include the token in test requests:
    $response = $this->post('/submit', [
        'g-recaptcha-response' => 'test-token',
        'name' => 'Test User',
    ]);
    
  • Edge Cases: Test invalid tokens and missing fields:
    $response = $this->post('/submit', ['name' => 'Test User']);
    $response->assertSessionHasErrors('g-recaptcha-response');
    

Gotchas and Tips

Pitfalls

  1. Missing JavaScript:

    • Issue: If NoCaptcha::renderJs() is omitted, the reCAPTCHA widget won’t render.
    • Fix: Ensure the JS is included before the widget in your Blade template.
  2. Token Validation Timing:

    • Issue: Invisible reCAPTCHA (displaySubmit) requires the form ID to auto-submit on success. If the form ID is incorrect or missing, the callback fails silently.
    • Fix: Verify the form ID matches the one in displaySubmit():
      {!! NoCaptcha::displaySubmit('my-form-id', 'Submit') !!}
      <form id="my-form-id" method="POST">
      
  3. Rate Limiting:

    • Issue: Google’s free tier limits reCAPTCHA requests to 1M/day. Exceeding this may trigger temporary bans.
    • Fix: Monitor usage via Google’s reCAPTCHA admin console or implement caching for repeated requests.
  4. Testing Quirks:

    • Issue: Mocking NoCaptcha::display() in tests returns a hidden input, which may bypass frontend validation.
    • Fix: Combine mocking with explicit token inclusion:
      NoCaptcha::shouldReceive('verifyResponse')->andReturn(true);
      $response = $this->post('/submit', ['g-recaptcha-response' => '1']);
      
  5. Laravel Version Mismatches:

    • Issue: Using the package with unsupported Laravel versions (e.g., 5.4) may cause autoloading errors.
    • Fix: Check the release notes for compatibility or use a specific branch (e.g., v1 for Laravel 4).

Debugging Tips

  • Validate the Token Manually: Use Google’s test response tool to verify your NOCAPTCHA_SECRET and NOCAPTCHA_SITEKEY.
  • Check Network Requests: Ensure the reCAPTCHA API call (https://www.google.com/recaptcha/api/siteverify) succeeds in browser dev tools or Laravel logs.
  • Enable Debugging: Add NOCAPTCHA_DEBUG=true to .env to log API responses (if supported in future versions).

Extension Points

  1. Custom Validation Logic:

    • Extend the validator by creating a custom rule:
      use Anhskohbo\NoCaptcha\Rules\Recaptcha;
      
      $rules = [
          'g-recaptcha-response' => [new Recaptcha(), 'required'],
      ];
      
  2. Fallback Mechanisms:

    • Implement a fallback for failed CAPTCHA validation (e.g., manual CAPTCHA or rate-limiting):
      if (!NoCaptcha::verifyResponse($token)) {
          // Fallback: Use a simple CAPTCHA or block the request
          return response()->json(['error' => 'Service unavailable'], 503);
      }
      
  3. Invisible reCAPTCHA (v3) Integration:

    • Use the package’s displaySubmit for v3 or manually integrate v3’s scoring API:
      $response = NoCaptcha::verifyResponse($token, 'v3');
      $score = $response['score']; // Use score for risk-based decisions
      
  4. Middleware for API Routes:

    • Create reusable middleware for API-wide CAPTCHA enforcement:
      public function handle($request, Closure $next) {
          if (!$request->hasValidRecaptcha()) { // Custom method
              return response()->json(['error' => 'Invalid CAPTCHA'], 403);
          }
          return $next($request);
      }
      

Configuration Quirks

  • Auto-Discovery: In Laravel 5.5+, the package auto-registers. If issues arise, manually register the service provider and facade alias.
  • Environment Variables: Ensure NOCAPTCHA_SECRET and NOCAPTCHA_SITEKEY are set in .env and cached (run php artisan config:cache if using caching).
  • Custom Attributes: The display() method accepts HTML attributes (e.g., data-theme, data-size). Refer to Google’s docs
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata