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

Livewire Recaptcha Laravel Package

dutchcodingcompany/livewire-recaptcha

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dutchcodingcompany/livewire-recaptcha
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="DutchCodingCompany\LivewireRecaptcha\LivewireRecaptchaServiceProvider"
    
  2. Configure Google reCAPTCHA: Add your SITE_KEY and SECRET_KEY to .env:

    RECAPTCHA_SITE_KEY=your_site_key
    RECAPTCHA_SECRET_KEY=your_secret_key
    
  3. First Use Case: Protect a Livewire action (e.g., form submission) by adding the directive to the method:

    use DutchCodingCompany\LivewireRecaptcha\HasRecaptcha;
    
    class MyComponent extends Component
    {
        use HasRecaptcha;
    
        public function submitForm()
        {
            $this->validate([...]);
    
            // Your logic here
        }
    
        public function recaptcha()
        {
            return $this->recaptcha('submitForm'); // Protects 'submitForm'
        }
    }
    
  4. Add reCAPTCHA Script: Include the script in your Livewire component's view:

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

Implementation Patterns

Core Workflows

1. Protecting Actions

  • Use the HasRecaptcha trait in your Livewire component.
  • Call $this->recaptcha('actionName') in a recaptcha() method to protect specific actions.
  • Example:
    public function recaptcha()
    {
        $this->recaptcha('submitForm'); // Protects submitForm
        $this->recaptcha('deleteItem'); // Protects deleteItem
    }
    

2. Dynamic Protection

  • Protect actions dynamically based on conditions:
    public function recaptcha()
    {
        if ($this->isAdmin) {
            return; // Skip reCAPTCHA for admins
        }
        $this->recaptcha('submitForm');
    }
    

3. Customizing reCAPTCHA Version

  • Specify the reCAPTCHA version (default: v3):
    $this->recaptcha('submitForm', version: 'v2'); // Uses v2
    $this->recaptcha('submitForm', version: 'v2-invisible'); // Uses v2-invisible
    

4. Handling Failures

  • Redirect or show errors when reCAPTCHA fails:
    public function submitForm()
    {
        if (!$this->verifyRecaptcha()) {
            session()->flash('error', 'reCAPTCHA verification failed.');
            return;
        }
        // Proceed with validation and logic
    }
    

5. Integration with Forms

  • Add the reCAPTCHA widget to your form (for v2/v2-invisible):
    <div class="g-recaptcha" data-sitekey="{{ config('services.recaptcha.site_key') }}"></div>
    
  • For v3, no widget is needed (handled automatically via JavaScript).

Advanced Patterns

1. Customizing Thresholds (v3)

  • Adjust the score threshold in config/livewire-recaptcha.php:
    'threshold' => 0.9, // Default is 0.5
    

2. Extending the Trait

  • Override the verifyRecaptcha() method for custom logic:
    public function verifyRecaptcha()
    {
        if (auth()->check()) {
            return true; // Skip for logged-in users
        }
        return parent::verifyRecaptcha();
    }
    

3. Testing

  • Use the recaptcha helper in tests to mock responses:
    $this->recaptcha->shouldReceive('verify')->andReturn(true);
    

4. Multi-Language Support

  • Set the reCAPTCHA language in the config:
    'language' => 'nl', // Dutch
    

Gotchas and Tips

Pitfalls

  1. Missing Script:

    • Forgetting to include the reCAPTCHA script (api.js) will cause silent failures. Always add it to your layout or component view.
  2. Incorrect Keys:

    • Using the wrong SITE_KEY or SECRET_KEY will result in failed verifications. Double-check .env:
      RECAPTCHA_SITE_KEY=your_site_key
      RECAPTCHA_SECRET_KEY=your_secret_key
      
  3. Caching Issues:

    • If reCAPTCHA fails intermittently, clear your browser cache or test in incognito mode. Google may block repeated requests.
  4. Version Confusion:

    • Mixing v2/v2-invisible (requires widget) with v3 (no widget) can lead to unexpected behavior. Ensure consistency in your implementation.
  5. Livewire Updates:

    • If upgrading Livewire, test the package thoroughly, as breaking changes may affect the directive.

Debugging Tips

  1. Check Logs:

    • Enable debug mode (APP_DEBUG=true) to see reCAPTCHA verification errors in Laravel logs.
  2. Verify API Responses:

    • Use tools like Postman to test the reCAPTCHA API directly with your SECRET_KEY to ensure it’s working.
  3. Inspect Network Requests:

    • Open browser dev tools (Network tab) to verify the reCAPTCHA verification request is being sent to Google’s endpoint:
      https://www.google.com/recaptcha/api/siteverify
      
  4. Test in Sandbox:

    • Use Google’s test keys (6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI) to avoid hitting request limits during development.

Extension Points

  1. Custom Verification Logic:

    • Override the verifyRecaptcha() method to add custom rules (e.g., IP-based exemptions).
  2. Event Listeners:

    • Listen for reCAPTCHA events (e.g., recaptcha.verified) by extending the package or using Laravel events.
  3. Frontend Customization:

    • Customize the reCAPTCHA widget’s appearance by passing options to the data-* attributes:
      <div class="g-recaptcha"
           data-sitekey="{{ config('services.recaptcha.site_key') }}"
           data-theme="dark"
           data-size="compact">
      </div>
      
  4. Rate Limiting:

    • Implement custom rate limiting for reCAPTCHA requests to prevent abuse (e.g., using Laravel’s throttle middleware).
  5. Multi-Tenant Support:

    • Store reCAPTCHA keys per tenant in a database and dynamically load them in the component:
      $siteKey = Tenant::find($tenantId)->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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager