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

Turnstile Laravel Package

lambda-studio/turnstile

Laravel package for Cloudflare Turnstile captcha validation. Includes a ValidTurnstile validation rule to verify the cf-turnstile-response token in requests, plus a simple Blade form example using your configured site key and Turnstile script.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Validation-Centric Design: The package excels in Laravel’s validation ecosystem, providing a ValidTurnstile rule that integrates seamlessly with Laravel’s form request validation system. This aligns perfectly with Laravel’s declarative validation approach, reducing boilerplate and improving maintainability.
  • Middleware and Facade Layers: Post-v2.0 additions (middleware, facade, service) enable both granular and global CAPTCHA enforcement, fitting well into Laravel’s middleware pipeline and service container architecture. The facade (Turnstile::verify()) abstracts API calls, promoting clean, testable code.
  • Cloudflare Turnstile Alignment: Directly implements Cloudflare’s Turnstile API, ensuring compliance with their latest security standards and reducing custom integration risks.

Integration Feasibility

  • Validation Rule: The core ValidTurnstile rule requires minimal setup—just apply it to form fields (e.g., cf-turnstile-response). This leverages Laravel’s existing validation infrastructure without disrupting workflows.
  • Frontend Agnosticism: Works with any frontend (Blade, React, Vue, etc.) as long as the Turnstile script and data-sitekey are included. This flexibility avoids locking the project into a specific frontend framework.
  • Configuration-Driven: Relies on Laravel’s config/turnstile.php, adhering to Laravel’s conventions for environment-specific configurations (e.g., .env files). This simplifies deployment across environments.

Technical Risk

  • Laravel Version Compatibility: Officially supports Laravel 8/9 but may introduce risks if the project uses older versions (e.g., <8.0) or newer edge releases (e.g., Laravel 10+). Test compatibility early, especially for facades and contracts.
  • Middleware Overhead: The ValidateTurnstile middleware adds latency if applied globally. Evaluate performance impact in high-traffic routes (e.g., admin dashboards) and restrict it to critical paths.
  • Error Handling: While custom exceptions exist, they may require additional handling (e.g., logging, user-facing messages) depending on project needs. Ensure error messages align with your UX standards.
  • Unreleased Features: Blade macros (e.g., @turnstile()) are planned but not implemented. If these are critical, consider implementing them manually or waiting for the package’s next release.
  • Cloudflare API Dependencies: Relies on Cloudflare’s Turnstile API, which may have downtime or rate limits. Implement fallback mechanisms (e.g., manual review) for critical forms.

Key Questions

  1. Validation Scope: Should the middleware validate all routes or only specific ones (e.g., /contact, /login)? Global middleware may impact performance.
  2. Rate Limiting: Does the project need additional rate-limiting for Turnstile API calls (not handled by the package)? Cloudflare’s rate limits should be monitored.
  3. Testing Strategy: How will Turnstile responses be mocked in unit/integration tests? Use Laravel’s Http::fake() or similar tools to simulate API responses.
  4. Frontend Integration: Will the package’s frontend implementation (Blade) conflict with existing UI frameworks (e.g., Livewire, Inertia)? Ensure consistency in widget rendering.
  5. Secret Management: How are config('turnstile.secret') values secured? Use environment variables (.env) or a secrets manager (e.g., Laravel Forge, Vault).
  6. Fallback Mechanisms: What happens if Cloudflare’s API is unavailable? Implement a fallback (e.g., disable CAPTCHA or use a manual review process).
  7. Customization Needs: Are the default error messages/translations sufficient, or will customization be required? The package supports i18n, but project-specific messages may need adjustments.
  8. API Usage: Beyond form submissions, will Turnstile be used for API endpoints (e.g., rate-limiting)? The package’s middleware/facade can support this, but additional logic may be needed.

Integration Approach

Stack Fit

  • Laravel-Optimized: The package is designed for Laravel’s ecosystem, leveraging its validation system, middleware pipeline, and service container. This reduces integration effort for projects already using Laravel.
  • PHP 8.1+ Requirement: Requires PHP 8.1+, which may necessitate runtime upgrades if the project uses older versions. Evaluate compatibility early.
  • Cloudflare Dependency: Requires internet access to Cloudflare’s Turnstile API. No offline mode is supported, which may impact internal or air-gapped environments.
  • Frontend Flexibility: Works with any frontend framework, but the provided Blade example may need adaptation for non-Blade setups (e.g., React, Vue).

Migration Path

  1. Installation:

    composer require lambda-studio/turnstile
    

    Publish the configuration file:

    php artisan vendor:publish --provider="LambdaStudio\Turnstile\TurnstileServiceProvider"
    

    Update config/turnstile.php with your Cloudflare Turnstile site_key and secret_key from .env.

  2. Configuration: Add the following to your .env file:

    TURNSTILE_SITE_KEY=your_site_key
    TURNSTILE_SECRET_KEY=your_secret_key
    
  3. Validation Integration: Apply the ValidTurnstile rule to form fields in your request validation logic:

    use LambdaStudio\Turnstile\Rules\ValidTurnstile;
    
    $request->validate([
        'cf-turnstile-response' => [
            'required',
            'string',
            new ValidTurnstile(),
        ],
    ]);
    
  4. Middleware Integration (Optional): Register the middleware in app/Http/Kernel.php for global validation:

    protected $middleware = [
        // ...
        \LambdaStudio\Turnstile\Http\Middleware\ValidateTurnstile::class,
    ];
    

    Or apply it to specific routes:

    Route::middleware(['turnstile'])->group(function () {
        // Routes requiring Turnstile validation
    });
    
  5. Frontend Implementation: Include the Turnstile script and widget in your forms. For Blade templates:

    <div class="cf-turnstile" data-sitekey="{{ config('turnstile.site_key') }}"></div>
    @error('cf-turnstile-response')
        <span>{{ $message }}</span>
    @enderror
    <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
    

Compatibility

  • Laravel Versions: Tested on Laravel 8.x/9.x. For Laravel 10+, verify compatibility, especially for facades and contracts, which may have breaking changes.
  • Existing CAPTCHA Systems: If using reCAPTCHA or other CAPTCHAs, ensure no conflicts (e.g., duplicate middleware or validation rules). Replace old CAPTCHA logic with the new ValidTurnstile rule.
  • CSRF Protection: Works alongside Laravel’s @csrf directive without conflicts. Ensure both are included in forms.
  • Frontend Frameworks: The package is frontend-agnostic, but the Blade example may need adaptation for frameworks like Livewire or Inertia. For Livewire, consider using Alpine.js or custom components to render the Turnstile widget.

Sequencing

  1. Phase 1: Core Validation

    • Implement the ValidTurnstile rule in critical forms (e.g., contact, registration, login).
    • Test validation logic and error handling in staging.
  2. Phase 2: Middleware Integration

    • Add the ValidateTurnstile middleware to routes or globally (if performance allows).
    • Monitor latency and error rates in production.
  3. Phase 3: API Integration (Optional)

    • Extend Turnstile validation to API endpoints using the facade or middleware.
    • Example: Validate Turnstile tokens in API rate-limiting logic.
  4. Phase 4: Customization

    • Customize error messages/translations if needed.
    • Implement Blade macros (e.g., @turnstile) if the package’s TODO items are critical.
  5. Phase 5: Monitoring and Optimization

    • Set up monitoring for Cloudflare API rate limits and Turnstile validation failures.
    • Optimize middleware routes to exclude low-risk endpoints.

Operational Impact

Maintenance

  • Low Overhead: The package is lightweight with minimal dependencies, and updates are likely infrequent (last release in Dec 2023). The MIT license ensures no vendor lock-in.
  • Configuration-Driven: Changes to Turnstile keys/secrets only require config updates (no code changes), simplifying maintenance.
  • Deprecation Risk: Low risk of deprecation, given Cloudflare’s commitment to Turnstile and Laravel’s backward compatibility. However, monitor Cloudflare’s API changes.
  • Dependency Updates: Keep an eye on Laravel and PHP version compatibility, especially if upgrading to Laravel 10+.

Support

  • Limited Community: With only 1 star and 0 dependents, community support is minimal. Rely on Cloudflare’s [official
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.
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
spatie/mailcoach-vapor