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 Google Recaptcha Laravel Package

nguyentranchung/laravel-google-recaptcha

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nguyentranchung/laravel-google-recaptcha
    

    Publish the config file:

    php artisan vendor:publish --provider="NguyenTrungChung\LaravelGoogleRecaptcha\LaravelGoogleRecaptchaServiceProvider"
    
  2. Configuration: Edit .env with your Google reCAPTCHA keys:

    RECAPTCHA_SITE_KEY=your_site_key_here
    RECAPTCHA_SECRET_KEY=your_secret_key_here
    RECAPTCHA_VERSION=v2  # or v3
    
  3. First Use Case: Add validation to a form (e.g., ContactFormRequest):

    use NguyenTrungChung\LaravelGoogleRecaptcha\Rules\Recaptcha;
    
    public function rules()
    {
        return [
            'g-recaptcha-response' => ['required', new Recaptcha],
        ];
    }
    
  4. Frontend Integration: Include the reCAPTCHA script in your Blade view:

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

    Add the reCAPTCHA widget to your form:

    <div class="g-recaptcha" data-sitekey="{{ config('recaptcha.site_key') }}"></div>
    

Implementation Patterns

Common Workflows

  1. Form Validation: Use the Recaptcha rule in Form Requests or manually in controllers:

    $validator = Validator::make($request->all(), [
        'g-recaptcha-response' => ['required', new Recaptcha],
    ]);
    
  2. Dynamic Site Key: Pass the site key dynamically to Blade views:

    // In a controller
    return view('form', ['siteKey' => config('recaptcha.site_key')]);
    
    <!-- In Blade -->
    <div class="g-recaptcha" data-sitekey="{{ $siteKey }}"></div>
    
  3. API Endpoints: For API-based forms, include the token in the request body:

    $validator = Validator::make($request->all(), [
        'recaptcha_token' => ['required', new Recaptcha],
    ]);
    
  4. Conditional Validation: Skip reCAPTCHA for trusted users (e.g., logged-in admins):

    $rules = ['g-recaptcha-response' => new Recaptcha];
    if (auth()->check() && auth()->user()->isAdmin()) {
        unset($rules['g-recaptcha-response']);
    }
    
  5. Custom Error Messages: Override default validation messages:

    $validator = Validator::make($request->all(), [
        'g-recaptcha-response' => ['required', new Recaptcha],
    ], [
        'g-recaptcha-response.required' => 'Please complete the CAPTCHA.',
        'g-recaptcha-response.recaptcha' => 'Invalid CAPTCHA. Please try again.',
    ]);
    

Integration Tips

  1. Laravel Fortify/Passport: Extend authentication requests with reCAPTCHA:

    public function rules()
    {
        return array_merge(parent::rules(), [
            'g-recaptcha-response' => ['required', new Recaptcha],
        ]);
    }
    
  2. Laravel Nova: Add reCAPTCHA to custom Nova actions or resource tools by extending the validation logic in the underlying controller.

  3. Queueable Jobs: Validate reCAPTCHA in a job before processing (e.g., newsletter subscriptions):

    public function handle()
    {
        $validator = Validator::make(['token' => $this->token], [
            'token' => ['required', new Recaptcha],
        ]);
        if ($validator->fails()) {
            throw new \Exception('Invalid CAPTCHA');
        }
        // Proceed with job
    }
    
  4. Testing: Use the Recaptcha::fake() method in tests to bypass validation:

    public function test_form_submission()
    {
        Recaptcha::fake();
        $response = $this->post('/contact', ['name' => 'Test']);
        $response->assertRedirect('/thank-you');
    }
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • The package was last updated in 2018 and lacks support for reCAPTCHA v3 (despite claiming compatibility). Use a modern alternative like bestmomo/laravel-recaptcha for v3 support.
    • Mitigation: Fork the repo or manually extend the Recaptcha rule to support v3.
  2. Config File Issues:

    • The published config file may not match your .env structure. Ensure:
      // config/recaptcha.php
      'site_key' => env('RECAPTCHA_SITE_KEY'),
      'secret_key' => env('RECAPTCHA_SECRET_KEY'),
      'version' => env('RECAPTCHA_VERSION', 'v2'),
      
    • Tip: Clear config cache after publishing:
      php artisan config:clear
      
  3. Frontend Script Loading:

    • The reCAPTCHA script must be loaded asynchronously (async defer) to avoid blocking page rendering. Place it just before </body>:
      <body>
          <!-- Your content -->
          <script src="https://www.google.com/recaptcha/api.js" async defer></script>
      </body>
      
  4. Token Expiry:

    • reCAPTCHA tokens expire after 2 minutes. Ensure your form submission handles this gracefully (e.g., show a "CAPTCHA expired" message if validation fails).
  5. Local Development:

    • Google reCAPTCHA requires HTTPS in production. For local testing, use a tool like ngrok to expose your site via HTTPS or mock the validation in tests (as shown above).

Debugging Tips

  1. Validation Failures:

    • Check the response from Google by logging the error:
      $validator = Validator::make([...], [...]);
      if ($validator->fails()) {
          \Log::error('reCAPTCHA Error:', $validator->errors()->toArray());
      }
      
    • Common errors:
      • invalid-domain-association: Ensure your domain is listed in the Google reCAPTCHA admin panel.
      • timeout-or-duplicate: Token expired or already used.
  2. Network Requests:

    • Use browser dev tools (Network tab) to inspect the POST request to https://www.google.com/recaptcha/api/siteverify. Verify the secret and response parameters are correct.
  3. Testing Locally:

    • For local testing, use the Recaptcha::fake() method to bypass validation during development:
      Recaptcha::fake(); // Add to a test or middleware
      

Extension Points

  1. Custom Validation Logic: Extend the Recaptcha rule to add custom logic (e.g., score thresholds for v3):

    use NguyenTrungChung\LaravelGoogleRecaptcha\Rules\Recaptcha as BaseRecaptcha;
    
    class CustomRecaptcha extends BaseRecaptcha
    {
        public function __construct($version = 'v3', $minScore = 0.9)
        {
            parent::__construct($version);
            $this->minScore = $minScore;
        }
    
        public function passes($attribute, $value)
        {
            if ($this->version === 'v3') {
                $response = $this->verify($value);
                return $response['success'] && $response['score'] >= $this->minScore;
            }
            return parent::passes($attribute, $value);
        }
    }
    
  2. Middleware for API: Create middleware to validate reCAPTCHA on API routes:

    namespace App\Http\Middleware;
    
    use Closure;
    use NguyenTrungChung\LaravelGoogleRecaptcha\Rules\Recaptcha;
    
    class ValidateRecaptcha
    {
        public function handle($request, Closure $next)
        {
            $validator = \Validator::make($request->all(), [
                'recaptcha_token' => ['required', new Recaptcha],
            ]);
            if ($validator->fails()) {
                return response()->json(['error' => 'Invalid CAPTCHA'], 422);
            }
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $routeMiddleware = [
        'recaptcha' => \App\Http\Middleware\ValidateRecaptcha::class,
    ];
    

    Use in routes:

    Route::post('/api/contact', function () { ... })->middleware('recaptcha');
    
  3. Event Listeners: Trigger events on successful/failed validation (e.g., log attempts):

    // In a service provider
    $validator
    
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.
nasirkhan/laravel-sharekit
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