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

Laravel Captcha Laravel Package

snipify-dev/laravel-captcha

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require snipify-dev/laravel-captcha
    php artisan vendor:publish --provider="SnipifyDev\LaravelCaptcha\CaptchaServiceProvider"
    

    This publishes the config file (config/captcha.php) and migration (if needed).

  2. Environment Configuration: Add your keys to .env:

    RECAPTCHA_SITE_KEY=your_site_key
    RECAPTCHA_SECRET_KEY=your_secret_key
    RECAPTCHA_VERSION=v3  # or v2
    
  3. First Use Case: Validate a form with reCAPTCHA v3:

    use SnipifyDev\LaravelCaptcha\Rules\Recaptcha;
    
    $request->validate([
        'g-recaptcha-response' => [new Recaptcha],
    ]);
    

Where to Look First

  • Config File: config/captcha.php (adjust thresholds, versions, and error messages).
  • Validation Rules: Rules/Recaptcha.php (extend or customize behavior).
  • Livewire Integration: Rules/LivewireRecaptcha.php (for Livewire-specific use).

Implementation Patterns

Standard Form Integration

  1. Form Setup:

    <!-- Blade -->
    <form method="POST" action="/submit">
        @csrf
        <div class="g-recaptcha" data-sitekey="{{ config('captcha.site_key') }}"></div>
        <button type="submit">Submit</button>
    </form>
    

    For v3, omit the <div> and handle validation server-side.

  2. Validation:

    $request->validate([
        'g-recaptcha-response' => ['required', new \SnipifyDev\LaravelCaptcha\Rules\Recaptcha],
    ]);
    

Livewire Integration

  1. Component Setup:

    use SnipifyDev\LaravelCaptcha\Rules\LivewireRecaptcha;
    
    public function rules()
    {
        return [
            'recaptcha_token' => [new LivewireRecaptcha],
        ];
    }
    
  2. Blade Template:

    @livewireScripts
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    

Dynamic Version Switching

Use the version() helper or config to switch between v2/v3:

use SnipifyDev\LaravelCaptcha\Facades\Captcha;

Captcha::version('v3')->verify($response);

API/Queue Jobs

For async verification (e.g., queue jobs):

use SnipifyDev\LaravelCaptcha\Facades\Captcha;

Captcha::verifyAsync($response)
    ->onSuccess(fn () => Log::info('Captcha passed'))
    ->onFailure(fn ($errors) => Log::error($errors))
    ->dispatch();

Gotchas and Tips

Pitfalls

  1. Testing Environments:

    • The package auto-disables reCAPTCHA in testing. Mock responses manually if needed:
      $this->partialMock(Captcha::class, function ($mock) {
          $mock->shouldReceive('verify')->andReturn(true);
      });
      
  2. Livewire Caching:

    • Ensure Livewire components re-render captcha tokens on refresh to avoid stale tokens.
  3. v2 vs. v3 Thresholds:

    • v3 requires a score threshold (default: 0.5). Adjust in config/captcha.php:
      'v3' => [
          'score_threshold' => 0.9, // Stricter threshold
      ],
      
  4. Secret Key Exposure:

    • Never expose RECAPTCHA_SECRET_KEY in client-side code. Use server-side validation only.

Debugging

  • Failed Verification:

    • Check config('captcha.debug') to log raw responses:
      'debug' => env('RECAPTCHA_DEBUG', false),
      
    • Enable in .env:
      RECAPTCHA_DEBUG=true
      
  • Livewire Errors:

    • Ensure recaptcha_token matches the field name in your Livewire component’s rules().

Extension Points

  1. Custom Rules: Extend the base rule for custom logic:

    use SnipifyDev\LaravelCaptcha\Rules\Recaptcha as BaseRecaptcha;
    
    class CustomRecaptcha extends BaseRecaptcha {
        public function passes($attribute, $value) {
            // Custom logic
            return parent::passes($attribute, $value);
        }
    }
    
  2. Event Listeners: Listen for verification events:

    use SnipifyDev\LaravelCaptcha\Events\RecaptchaVerified;
    
    RecaptchaVerified::listen(function ($event) {
        // Handle success
    });
    
  3. Middleware: Protect routes with captcha:

    use SnipifyDev\LaravelCaptcha\Http\Middleware\VerifyRecaptcha;
    
    Route::middleware([VerifyRecaptcha::class])->group(function () {
        // Protected routes
    });
    

Pro Tips

  • Local Development: Use a local reCAPTCHA tester (e.g., this tool) to simulate responses.

  • Performance: For high-traffic forms, cache verification results (e.g., Redis) to reduce API calls.

  • Multi-Tenant: Store keys per tenant in a database and dynamically load them:

    config(['captcha.site_key' => $tenant->recaptcha_site_key]);
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony