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

Laracaptcha Laravel Package

martian/laracaptcha

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require martian/laracaptcha
    

    Publish the config file:

    php artisan vendor:publish --provider="Martian\LaraCaptcha\LaraCaptchaServiceProvider"
    
  2. Configuration Edit .env with your chosen CAPTCHA service keys (e.g., HCAPTCHA_SITE_KEY, HCAPTCHA_SECRET_KEY or RECAPTCHA_SITE_KEY, RECAPTCHA_SECRET_KEY). Configure .env and config/laracaptcha.php:

    CAPTCHA_SERVICE=hcaptcha  # or 'recaptcha_v2'/'recaptcha_v3'
    
  3. First Use Case Validate a form with CAPTCHA in Laravel's FormRequest:

    use Martian\LaraCaptcha\Rules\Captcha;
    
    public function rules()
    {
        return [
            'captcha_token' => ['required', new Captcha],
        ];
    }
    

Implementation Patterns

Form Integration

  1. Blade Integration Render CAPTCHA widget in Blade:

    @captcha('hcaptcha')  <!-- or 'recaptcha_v2'/'recaptcha_v3' -->
    

    Outputs the HTML snippet (e.g., <div class="hcaptcha"></div>).

  2. API Integration Validate CAPTCHA in API requests:

    use Illuminate\Http\Request;
    use Martian\LaraCaptcha\Facades\LaraCaptcha;
    
    public function store(Request $request)
    {
        $validated = $request->validate([
            'token' => ['required', function ($attribute, $value, $fail) {
                if (!LaraCaptcha::verify($value)) {
                    $fail('CAPTCHA verification failed.');
                }
            }],
        ]);
    }
    
  3. Dynamic Service Switching Override the default service per request:

    LaraCaptcha::setService('recaptcha_v3')->verify($token);
    

Workflows

  1. Multi-Step Forms Store the CAPTCHA token in a session or database for multi-step validation:

    session(['captcha_token' => $request->token]);
    

    Validate later:

    $this->validate($request, ['token' => ['required', new Captcha(session('captcha_token'))]]);
    
  2. Conditional Validation Skip CAPTCHA for trusted users (e.g., logged-in admins):

    if (auth()->user()->isAdmin()) {
        $rules['captcha_token'] = ['sometimes', new Captcha];
    }
    
  3. Custom Error Messages Localize or customize CAPTCHA errors:

    $rules = ['token' => ['required', new Captcha]];
    $messages = ['token.captcha' => 'Please complete the CAPTCHA to proceed.'];
    $this->validate($request, $rules, $messages);
    

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • CAPTCHA tokens (especially reCAPTCHA v3) expire after 2 minutes. Store tokens temporarily if needed.
    • Fix: Use session() or cache() to persist tokens briefly.
  2. Environment Mismatch

    • Ensure .env keys match the config/laracaptcha.php settings.
    • Debug: Run php artisan config:clear after changes.
  3. API vs. Form Validation

    • reCAPTCHA v3 returns a score (e.g., 0.9). Adjust thresholds in config:
      'recaptcha_v3' => [
          'threshold' => 0.5, // Default: 0.5
      ],
      
    • hCAPTCHA/reCAPTCHA v2 use binary pass/fail.
  4. CORS Issues

    • If validating APIs, ensure your CAPTCHA service keys allow requests from your domain.
    • Fix: Whitelist domains in your CAPTCHA admin panel (e.g., Google reCAPTCHA "Authorized domains").

Debugging

  1. Verification Failures

    • Log the raw response for debugging:
      $response = LaraCaptcha::verify($token);
      \Log::info('CAPTCHA Response', $response);
      
    • Common issues:
      • Invalid token: Token expired or malformed.
      • IP/Domain mismatch: Token generated for a different domain/IP.
      • Rate limits: Exceeding CAPTCHA service quotas (e.g., 1,000 requests/day for reCAPTCHA v3).
  2. Silent Failures

    • Enable debug mode in config to log verification errors:
      'debug' => env('CAPTCHA_DEBUG', false),
      

Extension Points

  1. Custom Services Extend the package to support other CAPTCHA providers:

    // app/Providers/LaraCaptchaServiceProvider.php
    public function register()
    {
        LaraCaptcha::extend('custom', function () {
            return new CustomCaptchaService();
        });
    }
    
  2. Middleware for API Protection Create middleware to auto-validate CAPTCHA on specific routes:

    // app/Http/Middleware/ValidateCaptcha.php
    public function handle($request, Closure $next)
    {
        if (!$request->has('token') || !LaraCaptcha::verify($request->token)) {
            return response()->json(['error' => 'CAPTCHA required'], 403);
        }
        return $next($request);
    }
    

    Register in app/Http/Kernel.php:

    'api' => [
        \App\Http\Middleware\ValidateCaptcha::class,
    ],
    
  3. Testing Mock CAPTCHA responses in tests:

    // tests/TestCase.php
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('laracaptcha', [
            'service' => 'mock',
            'mock' => [
                'verify' => true, // or false to simulate failures
            ],
        ]);
    }
    

Performance Tips

  1. Lazy-Loading Defer CAPTCHA validation until the last step of a multi-step form to reduce server load.

  2. Caching Cache CAPTCHA responses for non-sensitive operations (if the service supports it):

    $response = cache()->remember("captcha_{$token}", 300, function () use ($token) {
        return LaraCaptcha::verify($token);
    });
    
  3. Async Validation For APIs, validate CAPTCHA asynchronously using Laravel Queues:

    dispatch(new ValidateCaptchaJob($token))->onQueue('captcha');
    
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.
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
spatie/flare-daemon-runtime