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

Filament Turnstile Laravel Package

coderflex/filament-turnstile

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require coderflex/filament-turnstile
    

    For Filament V2, use ^1.0 version.

  2. Configure Keys: Add Cloudflare Turnstile keys to .env:

    TURNSTILE_SITE_KEY=your_site_key
    TURNSTILE_SECRET_KEY=your_secret_key
    

    Use Cloudflare's dummy keys for testing.

  3. First Use Case: Add the Turnstile component to a Filament form:

    use Coderflex\FilamentTurnstile\Forms\Components\Turnstile;
    
    Turnstile::make('captcha')
        ->theme('auto')
        ->language('en-US')
        ->size('normal');
    

Where to Look First


Implementation Patterns

Core Workflows

  1. Form Integration:

    // In a Filament Form component
    public function form(Form $form): Form
    {
        return $form
            ->schema([
                // ... other fields
                Turnstile::make('captcha')
                    ->label('Verify You\'re Human')
                    ->required()
                    ->theme('dark'), // 'light', 'auto'
            ]);
    }
    
  2. Dynamic Reset on Validation Errors:

    // In a Livewire form component
    protected function onValidationError(ValidationException $exception): void
    {
        $this->dispatch('reset-captcha'); // Reset Turnstile after errors
        parent::onValidationError($exception);
    }
    
  3. Login Page Customization: Override Filament’s default login page to include Turnstile:

    // app/Filament/Pages/Auth/Login.php
    class Login extends AuthLogin
    {
        protected function getForms(): array
        {
            return [
                'form' => $this->form(
                    $this->makeForm()
                        ->schema([
                            $this->getEmailFormComponent(),
                            $this->getPasswordFormComponent(),
                            Turnstile::make('captcha')->theme('auto'),
                        ])
                ),
            ];
        }
    }
    
  4. Global Turnstile for All Forms: Register the component globally in AppServiceProvider:

    public function boot(): void
    {
        Filament::registerFormComponents([
            Turnstile::class,
        ]);
    }
    

Integration Tips

  • Conditional Rendering: Use visible() or hidden() methods to show/hide Turnstile based on logic:

    Turnstile::make('captcha')
        ->visible(fn ($record) => $record->isPublic())
    
  • Custom Validation: Validate the Turnstile response in your form’s rules():

    public function rules(): array
    {
        return [
            'captcha' => 'required|turnstile',
        ];
    }
    
  • Multi-Language Support: Dynamically set language based on user locale:

    Turnstile::make('captcha')
        ->language(app()->getLocale())
    
  • Asset Optimization: Lazy-load Turnstile scripts (enabled by default in v2.3.1+). No manual configuration needed.


Gotchas and Tips

Pitfalls

  1. Key Mismatch:

    • Issue: Turnstile fails silently if TURNSTILE_SITE_KEY/TURNSTILE_SECRET_KEY are missing or incorrect.
    • Fix: Verify keys in .env and test with Cloudflare’s dummy keys first.
  2. Multiple Instances:

    • Issue: Older versions (<v2.4.1) broke when multiple Turnstile instances were rendered.
    • Fix: Update to v2.4.1+ or manually ensure unique IDs for each instance:
      Turnstile::make('captcha_1')->uniqueId('unique_id_1')
      
  3. Event Dispatch Timing:

    • Issue: reset-captcha may not trigger if dispatched too early (e.g., before the component mounts).
    • Fix: Dispatch in onValidationError or after the form is rendered.
  4. Language Format:

    • Issue: Incorrect language format (e.g., en-US vs. en_us) causes rendering errors.
    • Fix: Use hyphenated format (en-US, fr-FR) as per Cloudflare’s docs.
  5. Asset Conflicts:

    • Issue: Turnstile scripts may conflict with other CAPTCHA libraries (e.g., reCAPTCHA).
    • Fix: Ensure no duplicate script tags are loaded. Use filament-turnstile:assets blade directive if needed.

Debugging

  • Turnstile Not Rendering: Check browser console for errors. Common causes:

    • Missing TURNSTILE_SITE_KEY.
    • Ad-blockers blocking Cloudflare’s scripts.
    • Conflicting CSS (e.g., display: none on the container).
  • Validation Failures: Ensure the turnstile validation rule is registered (handled automatically by laravel-turnstile).

  • Event Not Firing: Verify the event is dispatched after the Turnstile component is initialized:

    // Correct: Dispatch in onValidationError or mounted()
    protected function mounted(): void
    {
        $this->dispatch('reset-captcha');
    }
    

Extension Points

  1. Custom Themes/Styles: Override Turnstile’s CSS by publishing assets:

    php artisan vendor:publish --tag=filament-turnstile-assets
    

    Then modify resources/views/vendor/filament-turnstile/styles.blade.php.

  2. Custom Validation Logic: Extend the turnstile rule in AppServiceProvider:

    use Coderflex\LaravelTurnstile\Rules\Turnstile;
    
    public function boot(): void
    {
        $this->app['validator']->extend('turnstile', function ($attribute, $value, $parameters, $validator) {
            // Custom logic (e.g., IP-based restrictions)
            return Turnstile::validate($value, $parameters);
        });
    }
    
  3. Dynamic Site Key: Fetch the site key dynamically (e.g., from a config file or API):

    Turnstile::make('captcha')
        ->siteKey(config('turnstile.site_key'))
    
  4. Testing: Use Cloudflare’s test tokens in PHPUnit:

    $this->post('/form', [
        'captcha' => '03AHJ2-R47HLS32-5D...', // Test token
    ]);
    

Configuration Quirks

  • Default Values:

    • Theme: 'auto' (defaults to system preference).
    • Language: 'en-US' (fallback to browser locale if unsupported).
    • Size: 'normal' (use 'compact' for space-saving).
  • Environment-Specific Keys: Use .env.local or Laravel’s environment-based configs to manage keys per environment.

  • Filament V2/V3:

    • V2: Use ^1.0 version.
    • V3: Use ^2.0+ (includes global registration by default).
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky