Looking to hire Laravel developers? Try LaraJobs

turnstile-laravel-middleware maintained by ajnorman

Description
A package that adds middleware to check for bots using Cloudflare Turnstile
Author
Last update
2025/01/26 22:36 (dev-main)
License
Links
Downloads
2

Comments
comments powered by Disqus

Turnstile Laravel Middleware

⚠️ Documentation is incomplete and may be inaccurate. ⚠️

Static Badge Static Badge


Table of Contents


Introduction

This package provides a piece middleware for Laravel that integrates with Cloudflare Turnstile to protect your application from unwanted bots.


Requirements

  • PHP >= 8.2
  • Laravel >= 11.x
  • A Cloudflare account with Turnstile enabled and a site_key and secret_key generated. View the Cloudflare Turnstile documentation for more information.

Installation

You can install the package via composer:

composer require aj-norman/turnstile-laravel-middleware

Add the following environment variables to your .env file:

CF_TURNSTILE_SITE_KEY=<your-site-key>
CF_TURNSTILE_SECRET_KEY=<your-secret-key>

(Optional) Publish the configuration file:

php artisan vendor:publish --provider="AJNorman\Turnstile\TurnstileServiceProvider" --tag="config"

If you customize the configuration file, you may need to manually update the config/turnstile.php file in the future if the package is updated.

Add 'turnstile' => AJNorman\Turnstile\Middleware\TurnstileMiddleware::class middleware to the alias() array within the withMiddleware() method in your bootstrap/app.php file:

return Application::configure(basePath: dirname(__DIR__))
    //...
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            //...
            'turnstile' => \AJNorman\Turnstile\Middleware\TurnstileMiddleware::class,
        ]);
    })
    //...
    ->create();

The 'turnstile' key can be changed to any key you prefer.


Usage

You can apply the Turnstile middleware to any route or group of routes by adding 'turnstile' to the middleware array:

Route::post('/protected-route', function () {
    return 'This route is protected by Turnstile!';
})->middleware('turnstile');