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

Recaptcha Bundle Laravel Package

bghanem/recaptcha-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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"
    
  2. Configuration Edit .env or config/recaptcha.php:

    RECAPTCHA_SITE_KEY=your_site_key
    RECAPTCHA_SECRET_KEY=your_secret_key
    RECAPTCHA_VERSION=v3  # or v2
    
  3. 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']);
        }
    }
    

Implementation Patterns

Common Workflows

  1. Form Validation Use in FormRequest or controller:

    public function rules() {
        return [
            'g-recaptcha-response' => 'required|captcha',
        ];
    }
    
  2. Dynamic Version Handling Switch versions via config or runtime:

    $recaptcha = new Recaptcha(config('recaptcha.version'));
    
  3. API Integration For non-form submissions (e.g., AJAX):

    $response = $recaptcha->verify($token, ['remote_ip' => $request->ip()]);
    
  4. Custom Error Messages Override in AppServiceProvider:

    Recaptcha::setErrorMessage('Invalid verification');
    
  5. Laravel Nova/Forge Extend RecaptchaServiceProvider to auto-register in Nova/Forge.


Integration Tips

  • Laravel Mix/Webpack: Use @verbatim for raw JS if custom styling is needed.
  • Multi-Tenant Apps: Bind Recaptcha to tenant-specific keys via a resolver.
  • Testing: Mock Recaptcha in PHPUnit:
    $this->app->instance(Recaptcha::class, Mockery::mock(Recaptcha::class));
    

Gotchas and Tips

Pitfalls

  1. Version Mismatch

    • Ensure RECAPTCHA_VERSION matches the HTML snippet (v2 vs. v3).
    • Fix: Validate config in AppServiceProvider boot:
      if (!in_array(config('recaptcha.version'), ['v2', 'v3'])) {
          throw new \RuntimeException('Invalid recaptcha version');
      }
      
  2. Missing IP Address

    • v3 requires remote_ip for verification. Defaults to null if omitted.
    • Fix: Pass IP explicitly:
      $recaptcha->verify($token, ['remote_ip' => $request->ip()]);
      
  3. CSRF Token Conflicts

    • v2 may conflict with Laravel’s @csrf if not namespaced.
    • Fix: Use name="g-recaptcha-response" explicitly.
  4. Rate Limiting

    • Google may throttle requests. Cache responses for non-critical forms.

Debugging

  • Enable Logging Set RECAPTCHA_DEBUG=true in .env to log verification errors.

  • Test Tokens Use Google’s test keys (6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhQ) to debug locally.

Extension Points

  1. 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);
        }
    }
    
  2. Event Listeners Listen for recaptcha.failed events (register in EventServiceProvider):

    protected $listen = [
        'recaptcha.failed' => [\App\Listeners\LogCaptchaFailures::class],
    ];
    
  3. Dynamic Keys Override getSiteKey()/getSecretKey() in the service provider for environment-specific keys.

Performance

  • Lazy Loading: Defer recaptcha_v2()/recaptcha_v3() calls until needed (e.g., in a component).
  • Caching: Cache verification results for non-sensitive forms (e.g., newsletters).
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.
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament