### Install via Composer Source: https://github.com/laragear/turnstile/blob/2.x/README.md Installs the package using Composer. ```bash composer require laragear/turnstile ``` -------------------------------- ### Check challenge success with Turnstile::success() in a route Source: https://github.com/laragear/turnstile/blob/2.x/README.md After retrieving the challenge, use `success()` to check if it was successful. This example shows a route with the `turnstile:accept-failed` middleware that approves a comment when the challenge succeeds. ```php use App\Models\Comment; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Facades\Turnstile; Route::middleware('turnstile:accept-failed') ->post('comment', function (Request $request) { $request->validate([ 'body' => 'required|string', ]) $comment = Comment::make($request->only('body')); // If the challenge is successful, show the comment. if (Turnstile::success()) { $comment->approved_at = now(); } $comment->save(); return back(); }); ``` -------------------------------- ### Getting the correct client IP with CF-Connecting-IP header Source: https://github.com/laragear/turnstile/blob/2.x/README.md When behind a Cloudflare proxy, use the CF-Connecting-IP header to get the correct client IP. The header name is available as a constant in the Turnstile class. ```php use App\Uuid; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Challenge;use Laragear\Turnstile\Turnstile; Route::post('comment', function (Request $request, Turnstile $turnstile) { $challenge = $turnstile->getChallenge( $request->input($turnstile->key()), $request->header(Turnstile::HEADER) ); // ... }); ``` -------------------------------- ### Fake Turnstile Challenge with Turnstile::fake() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use the Turnstile facade's fake() method to simulate a Turnstile challenge response during testing. The method accepts any Turnstile Challenge attributes, allowing you to test different responses. In this example, a failed challenge is faked to verify that a comment is moderated. ```php use Laragear\Turnstile\Facades\Turnstile; public function test_comment_is_moderated_when_bot_detected() { Turnstile::fake([ 'success' => false ]); $this->post(['comment' => 'test_comment']); $this->assertDatabaseHas('comments', [ 'body' => 'test_comment', 'is_moderated' => true ]) } ``` -------------------------------- ### Validate with turnstile rule using Turnstile::key() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use the `key` method of the `Turnstile` facade to get the default form key and add custom validation rules. ```php use App\Rules\MyCustomRule; use Illuminate\Http\Request; use Laragear\Turnstile\Facades\Turnstile; public function create(Request $request) { $request->validate([ // ... Turnstile::key() => ['turnstile', new MyCustomRule], ]); // ... } ``` -------------------------------- ### Add turnstile middleware to route Source: https://github.com/laragear/turnstile/blob/2.x/README.md Attaches the 'turnstile' middleware to a POST route to validate Cloudflare Turnstile challenges. Avoid using on GET requests due to browser caching or inspection. ```php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::post('comment', function (Request $request) { // ... })->middleware('turnstile'); ``` -------------------------------- ### Inject Challenge into a route action Source: https://github.com/laragear/turnstile/blob/2.x/README.md Inject the `Laragear\Turnstile\Challenge` class into a route controller action to access the challenge instance, for example to check its action with `isAction()`. ```php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Challenge; Route::middleware('turnstile') ->post('comment', function (Request $request, Challenge $challenge) { if ($challenge->isAction('comment:store')) { // .... } // ... }); ``` -------------------------------- ### Environment configuration Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the environment for the library. When null, mirrors the application environment. On production, keys are required; on testing, challenges are faked; on other environments, testing keys are injected. Setting false disables rendering and challenge retrieval. ```php return [ 'env' => env('TURNSTILE_ENV'), ]; ``` -------------------------------- ### Programmatically Use Testing Keys with Enums Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use the useTestingSiteKey() and useTestingSecretKey() methods of the Turnstile facade to programmatically swap to testing keys. The corresponding enums (SiteKey and SecretKey) specify the desired behavior. ```php use Laragear\Turnstile\Enums\SiteKey; use Laragear\Turnstile\Enums\SecretKey; use Laragear\Turnstile\Facades\Turnstile; Turnstile::useTestingSiteKey(SiteKey::ForceInteraction); Turnstile::useTestingSecretKey(SecretKey::Fails); ``` -------------------------------- ### Environment variables for credentials Source: https://github.com/laragear/turnstile/blob/2.x/README.md Environment variables to set the Site Key and Secret Key. ```dotenv TURNSTILE_SITE_KEY=... TURNSTILE_SECRET_KEY=... ``` -------------------------------- ### Publish Turnstile configuration file Source: https://github.com/laragear/turnstile/blob/2.x/README.md Publishes the package configuration file for fine-tuning the Challenge verification. ```bash php artisan vendor:publish --provider="Laragear\Turnstile\TurnstileServiceProvider" --tag="config" ``` -------------------------------- ### Full Turnstile configuration array Source: https://github.com/laragear/turnstile/blob/2.x/README.md The complete configuration array returned after publishing. Includes environment, key, client options, site/secret keys, and interstitial settings. ```php env('TURNSTILE_ENV', env('APP_ENV')), 'key' => \Laragear\Turnstile\Turnstile::KEY, 'client' => array_merge_recursive([ \GuzzleHttp\RequestOptions::VERSION => 2.0, ], defined('CURL_VERSION_HTTP3') && curl_version()['features'] & CURL_VERSION_HTTP3 ? ['curl' => [CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_3]] : [], ), 'site_key' => env('TURNSTILE_SITE_KEY'), 'secret_key' => env('TURNSTILE_SECRET_KEY'), 'interstitial' => [ 'key' => '_turnstile.interstitial', 'view' => 'turnstile::interstitial', 'route' => 'turnstile.interstitial', 'duration' => true, ], ]; ``` -------------------------------- ### Credentials configuration Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the Site Key and Secret Key for Turnstile. Use environment variables instead of changing the array directly. ```php return [ 'site_key' => env('TURNSTILE_SITE_KEY'), 'secret_key' => env('TURNSTILE_SECRET_KEY'), ]; ``` -------------------------------- ### Preconnect resource hint Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set the preconnect attribute to add a resource hint to Cloudflare servers for performance optimization. ```blade ``` ```html ``` -------------------------------- ### Configure middleware with TurnstileMiddleware::acceptFailed() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Uses the TurnstileMiddleware class to allow the route to continue even if the challenge fails. This is an alternative to the string middleware name. ```php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Middleware\TurnstileMiddleware; Route::post('comment', function (Request $request) { // ... })->middleware(TurnstileMiddleware::acceptFailed()) ``` -------------------------------- ### Custom challenge key with TurnstileMiddleware::input() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Configures the middleware to check a custom form key instead of the default 'cf-turnstile-response'. Use when the frontend uses a different key name. ```php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Middleware\TurnstileMiddleware; Route::post('comment', function (Request $request) { // ... })->middleware(TurnstileMiddleware::input('my-response-token-key')) ``` -------------------------------- ### Accept failed challenges with TurnstileMiddleware::acceptFailed() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Allows the route to continue even if the challenge fails. Use when you want to handle failures gracefully. ```php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Middleware\TurnstileMiddleware; Route::post('comment', function (Request $request) { // ... })->middleware(TurnstileMiddleware::acceptFailed()); ``` -------------------------------- ### Disable async and defer Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set :async="false" and :defer="false" to render the script without those attributes. ```blade ``` ```html ``` -------------------------------- ### HTTP client options configuration Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets options for the outgoing request to Cloudflare Turnstile servers. By default uses HTTP/3 with fallback to HTTP/2 if cURL lacks HTTP/3 support. ```php return [ 'client' => array_merge_recursive([ \GuzzleHttp\RequestOptions::VERSION => 2.0, // ...Add your config here. ], // This will detect if your cURL version has HTTP/3 support and prioritize it. defined('CURL_VERSION_HTTP3') && curl_version()['features'] & CURL_VERSION_HTTP3 ? ['curl' => [CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_3]] : [], ), ]; ``` -------------------------------- ### Check Turnstile action with isAction() in a Route Source: https://github.com/laragear/turnstile/blob/2.x/README.md Access the Cloudflare Turnstile Challenge object via the `challenge()` method and use `isAction()` to verify the action value. If the action does not match, the request is rejected with an error. ```php use App\Models\Comment; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Requests\TurnstileRequest; Route::post('comment', function (TurnstileRequest $request) { $request->validate([ 'body' => 'required|string' ]); if ($request->isAction('comment:store')) { return back()->withErrors('Invalid action'); } return Comment::create($request->only('body')); }) ``` -------------------------------- ### Basic script component in HTML head Source: https://github.com/laragear/turnstile/blob/2.x/README.md Place the component in the tag to load the Cloudflare Turnstile script with async and defer by default. ```blade My application ... ``` -------------------------------- ### Customize Interstitial Route Path and Middleware Source: https://github.com/laragear/turnstile/blob/2.x/README.md Changes the default path and middleware for the interstitial routes. The first parameter sets the path to '/challenge', and the second sets the middleware to 'guest'. ```php use Laragear\Turnstile\Http\Controllers\InterstitialController; InterstitialController::register('/challenge', 'guest'); ``` -------------------------------- ### TurnstileWidget::executionRender() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the execution of the widget challenge as it renders. ```APIDOC ## TurnstileWidget::executionRender() ### Description Sets the execution of the widget challenge as it renders. ### Method executionRender() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->executionRender() ``` ``` -------------------------------- ### TurnstileWidget::system() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the theme of the widget to system/browser default. ```APIDOC ## TurnstileWidget::system() ### Description Sets the theme of the widget to system/browser default. ### Method system() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->system() ``` ``` -------------------------------- ### TurnstileWidget::executionExecute() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the execution of the widget challenge on manual execution. ```APIDOC ## TurnstileWidget::executionExecute() ### Description Sets the execution of the widget challenge on manual execution. ### Method executionExecute() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->executionExecute() ``` ``` -------------------------------- ### Register Global Interstitial Middleware Source: https://github.com/laragear/turnstile/blob/2.x/README.md Appends the 'turnstile.interstitial' middleware to the 'web' middleware group globally. This is done in the 'bootstrap/app.php' file or 'App\Providers\AppServiceProviders'. ```php use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Middleware; return Application::configure(basePath: dirname(__DIR__)) ->withMiddleware(function (Middleware $middleware) { $middleware->appendToGroup('web', 'turnstile.interstitial'); }) ->create(); ``` -------------------------------- ### TurnstileWidget::light() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the theme of the widget to light. ```APIDOC ## TurnstileWidget::light() ### Description Sets the theme of the widget to light. ### Method light() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->light() ``` ``` -------------------------------- ### Customize script injection with withScript() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use withScript() to push the Turnstile script to a custom stack and pass additional attributes to the widget. The stack defaults to 'scripts' if not specified. ```php use Laragear\Turnstile\Filament\Forms\TurnstileWidget; TurnstileWidget::make()->withScript( stack: 'head-scripts', attributes: ['meta' => true] ); ``` -------------------------------- ### Handle JSON Response for Interstitial Challenge Source: https://github.com/laragear/turnstile/blob/2.x/README.md Shows how to handle the JSON response thrown by the interstitial middleware when the request requires JSON. The response includes a 'redirect_url' key that should be used to redirect the user to the interstitial controller. ```javascript response = await $fetch('/comment', 'POST', {body: 'My Comment'}); if (response.isStatus(400) && response.hasJson('redirect_url')) { window.location.href = response.json('redirect_url') } ``` -------------------------------- ### TurnstileWidget::withScript(string $stack = 'scripts', array $attributes = []) Source: https://github.com/laragear/turnstile/blob/2.x/README.md Configures the script injection stack and additional attributes for the widget. ```APIDOC ## TurnstileWidget::withScript(string $stack = 'scripts', array $attributes = []) ### Description Configures the script injection stack and additional attributes for the widget. ### Method withScript(string $stack = 'scripts', array $attributes = []) ### Parameters - **$stack** (string) - Optional - The stack where the script should be pushed. Defaults to 'scripts'. - **$attributes** (array) - Optional - Additional attributes to pass to the widget. ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->withScript( stack: 'head-scripts', attributes: ['meta' => true] ) ``` ``` -------------------------------- ### Check action name with TurnstileMiddleware::action() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Validates that the challenge's action name matches the given value. Throws a validation exception if the action doesn't match. ```php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Middleware\TurnstileMiddleware; Route::post('comment', function (Request $request) { // ... })->middleware(TurnstileMiddleware::action('comment:store')); ``` -------------------------------- ### Default script tag output Source: https://github.com/laragear/turnstile/blob/2.x/README.md The component renders a script tag with async and defer attributes by default. ```html ``` -------------------------------- ### Retrieving the Challenge on failure with try-catch Source: https://github.com/laragear/turnstile/blob/2.x/README.md If challenge retrieval fails due to a server or backend error, catch the InvalidChallengeException and retrieve the Challenge from the exception to proceed. ```php use Laragear\Turnstile\Exceptions\InvalidChallengeException;use Laragear\Turnstile\Facades\Turnstile; try { $challenge = Turnstile::getChallenge(); } catch (InvalidChallengeException $exception) { $challenge = $exception->getChallenge(); } ``` -------------------------------- ### Form key configuration Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the default key to check in the Request for the Turnstile response. Default is 'cf-turnstile-response'. ```php return [ 'key' => \Laragear\Turnstile\Turnstile::KEY, ]; ``` -------------------------------- ### TurnstileWidget::compact() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the size of the widget to compact. ```APIDOC ## TurnstileWidget::compact() ### Description Sets the size of the widget to compact. ### Method compact() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->compact() ``` ``` -------------------------------- ### Route with turnstile middleware Source: https://github.com/laragear/turnstile/blob/2.x/README.md Protects a POST route with the 'turnstile' middleware to verify Cloudflare Turnstile responses. ```php use Illuminate\Support\Facades\Route; Route::post('login', function () { // ... })->middleware('turnstile'); ``` -------------------------------- ### Retrieve a saved challenge with Turnstile::challenge() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use the `challenge()` method on the `Turnstile` facade to retrieve an already saved Turnstile Challenge from the Application Container. ```php use Laragear\Turnstile\Facades\Turnstile; $challenge = Turnstile::challenge(); ``` -------------------------------- ### TurnstileWidget::appearanceExecute() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the appearance of the widget to appear on manual execution. ```APIDOC ## TurnstileWidget::appearanceExecute() ### Description Sets the appearance of the widget to appear on manual execution. ### Method appearanceExecute() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->appearanceExecute() ``` ``` -------------------------------- ### Skip and handle Turnstile challenge status Source: https://github.com/laragear/turnstile/blob/2.x/README.md Override skipTurnstileValidation() and handleTurnstileChallengeStatus() to control when the challenge runs and whether it succeeds, e.g., skipping for admins and checking the action. ```php use Illuminate\Support\Str; use Laragear\Turnstile\Challenge; /** * Check if the Turnstile challenge validation should be skipped if authenticated. */ protected function skipTurnstileValidation(): bool { // Do not run if the user is an admin. return auth('admins')->check(); } /** * Handles the Turnstile challenge and returns true or false if it has succeeded or failed. */ protected function handleTurnstileChallengeStatus(Challenge $challenge): bool { return $challenge->successful && $challenge->isAction(Str::snake(static::class)); } ``` -------------------------------- ### Retrieve challenge from request with getChallengeFromRequest() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use `getChallengeFromRequest()` to automatically resolve the Request from the Container and find the token using the default key name. ```php use Laragear\Turnstile\Facades\Turnstile; $challenge = Turnstile::getChallengeFromRequest(); ``` -------------------------------- ### TurnstileWidget::make() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Creates a new TurnstileWidget field instance for use in Filament forms. It automatically injects the Turnstile script and renders the widget, with validation on form submission. ```APIDOC ## TurnstileWidget::make() ### Description Creates a new TurnstileWidget field instance for use in Filament forms. It automatically injects the Turnstile script and renders the widget, with validation on form submission. ### Method make() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make() ``` ``` -------------------------------- ### Bypass middleware for authenticated users with TurnstileMiddleware::auth() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Configures the middleware to skip the challenge if the user is authenticated via the default guard. Use specific guard names as arguments to check other guards. ```php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Middleware\TurnstileMiddleware; Route::post('comment', function (Request $request) { // ... })->middleware(TurnstileMiddleware::auth()); ``` ```php use Laragear\Turnstile\Http\Middleware\TurnstileMiddleware; TurnstileMiddleware::auth('admin'); ``` -------------------------------- ### Retrieve challenge without saving with getChallenge(..., save: false) Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set the `save` parameter to `false` to avoid saving the challenge into the Application Container. ```php use Laragear\Turnstile\Facades\Turnstile; $challenge = Turnstile::getChallenge('token', save: false); ``` -------------------------------- ### Register Interstitial Routes and Apply Middleware Source: https://github.com/laragear/turnstile/blob/2.x/README.md Registers the default interstitial challenge routes and applies the 'turnstile.interstitial' middleware to a route group. The middleware forces first-time visitors to complete a Turnstile challenge before redirecting to the intended route. ```php use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Controllers\InterstitialController; Route::group(function () { // ... })->middleware('turnstile.interstitial'); InterstitialController::register(); ``` -------------------------------- ### Vue component using site key from meta tag Source: https://github.com/laragear/turnstile/blob/2.x/README.md Retrieve the site key from the meta tag with name 'turnstile-sitekey' and use it in a Vue component. ```vue ``` -------------------------------- ### TurnstileWidget::flexible() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the size of the widget to flexible. ```APIDOC ## TurnstileWidget::flexible() ### Description Sets the size of the widget to flexible. ### Method flexible() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->flexible() ``` ``` -------------------------------- ### Idempotency Keys with getChallengeFromRequest Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use a UUID as an idempotency key to avoid errors when the same challenge token is submitted multiple times. The UUID is generated from a hash of the request input and passed to the getChallengeFromRequest method. ```php use App\Uuid; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Challenge; use Laragear\Turnstile\Facades\Turnstile; Route::post('comment', function (Request $request) { // Generate a UUID using the hash of the input as the seed. $uuid = Uuid::generateWithSeed(md5(json_encode($request->input('body'))); Turnstile::getChallengeFromRequest(idempotencyKey: $uuid); // ... }); ``` -------------------------------- ### Run on Precognitive requests with TurnstileMiddleware::onPrecognitive() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Enables the middleware to run on Precognitive requests, which are skipped by default. Use when validation has side effects. ```php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Middleware\TurnstileMiddleware; Route::post('comment', function (Request $request) { // ... })->middleware(TurnstileMiddleware::onPrecognitive()); ``` -------------------------------- ### Set Testing Site Key on Widget Source: https://github.com/laragear/turnstile/blob/2.x/README.md For the widget, change the site key using the site-key attribute with the enum case name as value. The value can be in kebab-case, snake_case, camelCase, or StudlyCaps, as they are normalized for you. ```blade ``` -------------------------------- ### Interstitial configuration Source: https://github.com/laragear/turnstile/blob/2.x/README.md Controls the interstitial middleware behavior: session key, view, route name, and reminder duration. 'duration' true means forever, integer means minutes. ```php 'interstitial' => [ 'key' => '_turnstile.interstitial', 'view' => 'turnstile::interstitial', 'route' => 'turnstile.interstitial', 'duration' => true, ], ``` -------------------------------- ### Script with meta tag for site key Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set the meta attribute to render a meta tag containing your Turnstile site-key for use in JavaScript frontend. ```blade My application ... ``` ```html ``` -------------------------------- ### Add TurnstileWidget to a Filament form Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use the Laragear\Turnstile\Filament\Forms\TurnstileWidget field in a Filament page form to automatically inject the Turnstile script and render the widget. The challenge is validated only on complete form submission. ```php use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; use Filament\Forms\Concerns\InteractsWithForms; use Filament\Forms\Contracts\HasForms; use Filament\Pages\Page; use Filament\Schemas\Schema; use Laragear\Turnstile\Filament\Forms\TurnstileWidget; class ContactPage extends Page implements HasForms { use InteractsWithForms; public function form(Schema $schema) : Schema { return $schema->components([ TextInput::make('subject')->required(), Textarea::make('message')->required(), // Add the Turnstile Widget TurnstileWidget::make(), ]); } } ``` -------------------------------- ### TurnstileWidget::callback(string $functionName) Source: https://github.com/laragear/turnstile/blob/2.x/README.md Adds an additional function names to execute on successful challenges. ```APIDOC ## TurnstileWidget::callback(string $functionName) ### Description Adds an additional function names to execute on successful challenges. ### Method callback(string $functionName) ### Parameters - **$functionName** (string) - Required - The function name to execute. ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->callback('myCallback') ``` ``` -------------------------------- ### Custom onload callback with explicit rendering Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set a custom callback name with the onload attribute to execute once the script is loaded, useful for explicit rendering. ```blade ``` ```html ``` -------------------------------- ### Check for missing challenge and fallback to request Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use `missingChallenge()` to check if a Challenge was not received and saved, then fallback to `getChallengeFromRequest()`. Otherwise, retrieve the saved challenge with `challenge()`. ```php use Laragear\Turnstile\Facades\Turnstile; if (Turnstile::missingChallenge()) { return Turnstile::getChallengeFromRequest(); } return Turnstile::challenge(); ``` -------------------------------- ### TurnstileWidget::implicit(bool $condition = true) Source: https://github.com/laragear/turnstile/blob/2.x/README.md Makes the widget be rendered automatically by the script. ```APIDOC ## TurnstileWidget::implicit(bool $condition = true) ### Description Makes the widget be rendered automatically by the script. ### Method implicit(bool $condition = true) ### Parameters - **$condition** (bool) - Optional - Defaults to true. Whether to render implicitly. ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->implicit() ``` ``` -------------------------------- ### Manually validate challenge with getChallenge() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use `getChallenge()` to retrieve the Challenge from Cloudflare Turnstile servers using the response token and optionally the IP. Returns a `Laragear\Turnstile\Challenge` instance. ```php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Facades\Turnstile; Route::post('comment', function (Request $request) { $challenge = Turnstile::getChallenge( $request->input('cf-turnstile-response'), $request->ip() ); if ($challenge->failed || $challenge->isNotAction('comment:store')) { // ... throw an exception. } // ... save the comment. }) ``` -------------------------------- ### Hide Interstitial Routes for Authenticated Users Source: https://github.com/laragear/turnstile/blob/2.x/README.md Registers the interstitial routes with the 'guest' middleware to hide them from authenticated users. This is recommended when the interstitial middleware is skipped for authenticated users. ```php use Laragear\Turnstile\Http\Controllers\InterstitialController; InterstitialController::register(middleware: 'guest'); ``` -------------------------------- ### Widget with HTML and data attributes Source: https://github.com/laragear/turnstile/blob/2.x/README.md Pass HTML attributes and data attributes to change widget behavior, such as data-action and data-error-callback. ```blade ``` ```html
``` -------------------------------- ### Validate with turnstile rule using Turnstile::rules() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use the `turnstile` rule to check the Turnstile challenge in request data. Unpack the default rules from the `rules()` method of the `Turnstile` facade. ```php use Illuminate\Http\Request; use Laragear\Turnstile\Facades\Turnstile; public function create(Request $request) { $request->validate([ 'comment' => 'required|string', // 'cf-turnstile-response' => 'turnstile', ...Turnstile::rules() ]); // ... } ``` -------------------------------- ### Challenge::isAction() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Checks if the challenge is associated with a specific action. This method is available on the injected Challenge instance. ```APIDOC ## Challenge::isAction() ### Description Checks if the challenge is associated with a specific action. This method is available on the injected Challenge instance. ### Method `isAction(string $action)` ### Parameters - **$action** (string) - Required - The action name to check against. ### Return Value - **bool** - `true` if the challenge is for the given action, `false` otherwise. ### Example ```php use Laragear\Turnstile\Challenge; if ($challenge->isAction('comment:store')) { // Action matches } ``` ``` -------------------------------- ### Blade widget for guests only Source: https://github.com/laragear/turnstile/blob/2.x/README.md Shows the Turnstile widget only to guests of the 'admin' guard, complementing the auth bypass. Place inside a form to render the challenge. ```blade
@guest('admin') @endguest ``` -------------------------------- ### TurnstileWidget::languageApp() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the language of the widget to application locale. ```APIDOC ## TurnstileWidget::languageApp() ### Description Sets the language of the widget to application locale. ### Method languageApp() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->languageApp() ``` ``` -------------------------------- ### TurnstileWidget::languageAuto() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the language of the widget to browser locale. ```APIDOC ## TurnstileWidget::languageAuto() ### Description Sets the language of the widget to browser locale. ### Method languageAuto() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->languageAuto() ``` ``` -------------------------------- ### Customize Turnstile key and rules in form request Source: https://github.com/laragear/turnstile/blob/2.x/README.md Override `getTurnstileKey()` to change the request key where the response token is found, and `getTurnstileRules()` to customize validation rules. Use the `turnstile` rule for validation. ```php namespace App\Http\Requests; use Laragear\Turnstile\Http\Requests\TurnstileRequest; class CommentStoreRequest extends TurnstileRequest { public function getTurnstileKey() { return '_cf-custom-key'; } protected function getTurnstileRules() { // Skip if the user is authenticated. return 'turnstile:auth' } // ... } ``` -------------------------------- ### TurnstileWidget::actionName(string $functionName) Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the action name for the challenge. ```APIDOC ## TurnstileWidget::actionName(string $functionName) ### Description Sets the action name for the challenge. ### Method actionName(string $functionName) ### Parameters - **$functionName** (string) - Required - The action name. ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->actionName('myAction') ``` ``` -------------------------------- ### Skip Interstitial for Authenticated Users Source: https://github.com/laragear/turnstile/blob/2.x/README.md Adds the 'auth' keyword to the middleware to skip the challenge for authenticated users. The route is defined with the middleware 'turnstile.interstitial:auth'. ```php use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Middleware\InterstitialMiddleware; Route::get('photos', function () { // .. })->middleware('turnstile.interstitial:auth'); ``` -------------------------------- ### Skip Interstitial for Specific Guards Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets specific guards to check for skipping the middleware. The guards are specified as 'auth=guard&guard..' in the middleware parameter. ```php use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Middleware\InterstitialMiddleware; Route::get('photos', function () { // .. })->middleware('turnstile.interstitial:auth=web&admins'); ``` -------------------------------- ### Set Testing Keys via Environment Variables Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set the Turnstile testing keys by changing the TURNSTILE_SITE_KEY and TURNSTILE_SECRET_KEY environment variables in your .env file. The enum names are matched automatically to the corresponding testing key. This does not work in production environments. ```dotenv TURNSTILE_SITE_KEY=ForceInteraction TURNSTILE_SECRET_KEY=Fails ``` -------------------------------- ### Turnstile::success() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Checks if the retrieved Turnstile Challenge was successful. Must be invoked after the challenge has been retrieved. ```APIDOC ## Turnstile::success() ### Description Checks if the retrieved Turnstile Challenge was successful. Must be invoked after the challenge has been retrieved. ### Method `success()` ### Parameters None ### Return Value - **bool** - `true` if the challenge was successful, `false` otherwise. ### Example ```php use Laragear\Turnstile\Facades\Turnstile; if (Turnstile::success()) { // Challenge succeeded } ``` ``` -------------------------------- ### TurnstileWidget::dark() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the theme of the widget to dark. ```APIDOC ## TurnstileWidget::dark() ### Description Sets the theme of the widget to dark. ### Method dark() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->dark() ``` ``` -------------------------------- ### Custom meta tag name Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set a custom name for the meta tag by providing a value to the meta attribute. ```blade ``` ```html ``` -------------------------------- ### Bypass rule with multiple guards using turnstile:auth=admin,developer Source: https://github.com/laragear/turnstile/blob/2.x/README.md Add a list of guards to check by adding them after `=` and separating them by `,`. ```php $request->validate([ Turnstile::key() => 'turnstile:auth=admin,developer', ]); ``` -------------------------------- ### TurnstileWidget::normal() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the size of the widget to normal. ```APIDOC ## TurnstileWidget::normal() ### Description Sets the size of the widget to normal. ### Method normal() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->normal() ``` ``` -------------------------------- ### Extend TurnstileRequest to create a custom form request Source: https://github.com/laragear/turnstile/blob/2.x/README.md Create a form request class by extending `TurnstileRequest` instead of the base `FormRequest`. The Turnstile validation runs before your form request authorization and rules to avoid side effects. ```php namespace App\Http\Requests; use Laragear\Turnstile\Http\Requests\TurnstileRequest; class CommentStoreRequest extends TurnstileRequest { public function rules(): array { return [ 'body' => 'required|string' ]; } } ``` -------------------------------- ### Validate Turnstile Challenge in a Route using TurnstileRequest Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use the TurnstileRequest instance in a route closure to automatically validate the Turnstile Challenge before your own validation rules. The request checks for the `cf-turnstile-response` key by default and requires a successful Challenge. ```php use App\Models\Comment; use Illuminate\Support\Facades\Route; use Laragear\Turnstile\Http\Requests\TurnstileRequest; Route::post('comment', function (TurnstileRequest $request) { $request->validate([ 'body' => 'required|string' ]); return Comment::create($request->only('body')); }) ``` -------------------------------- ### TurnstileWidget::tabindex(int $tabindex) Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the tab order of the widget to one set. ```APIDOC ## TurnstileWidget::tabindex(int $tabindex) ### Description Sets the tab order of the widget to one set. ### Method tabindex(int $tabindex) ### Parameters - **$tabindex** (int) - Required - The tab index value. ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->tabindex(1) ``` ``` -------------------------------- ### TurnstileWidget::appearanceAlways() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the appearance of the widget to always appear. ```APIDOC ## TurnstileWidget::appearanceAlways() ### Description Sets the appearance of the widget to always appear. ### Method appearanceAlways() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->appearanceAlways() ``` ``` -------------------------------- ### Turnstile::challenge() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Retrieves an already saved Turnstile Challenge from the Application Container. Use this method after the challenge has been received and saved. ```APIDOC ## Turnstile::challenge() ### Description Retrieves an already saved Turnstile Challenge from the Application Container. ### Method `challenge()` ### Parameters None ### Return Value - **Challenge** - The saved Turnstile Challenge instance. ### Example ```php use Laragear\Turnstile\Facades\Turnstile; $challenge = Turnstile::challenge(); ``` ``` -------------------------------- ### Manually validate Turnstile challenge Source: https://github.com/laragear/turnstile/blob/2.x/README.md After disabling automatic validation, call validateTurnstile() manually after validate() to verify the challenge. ```php public function create() { $validated = $this->validate(); // ... $this->validateTurnstile(); Ball::create($validated); } ``` -------------------------------- ### Explicit rendering script component Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set :explicit="true" to make widgets render only explicitly by your frontend JavaScript. ```blade ``` ```html ``` -------------------------------- ### Accept failed challenges with turnstile:accept-failed Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set the `accept-failed` parameter to not check if the challenge is successful. Useful to retrieve the response later and use `success()` and `failed()` methods. ```php use Illuminate\Http\Request; use Laragear\Turnstile\Facades\Turnstile; public function create(Request $request) { $request->validate([ Turnstile::key() => 'required|turnstile:accept-failed' ]); if (Turnstile::success()) { // ... } } ``` -------------------------------- ### TurnstileWidget::language(string $lang) Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the language of the widget to given locale. ```APIDOC ## TurnstileWidget::language(string $lang) ### Description Sets the language of the widget to given locale. ### Method language(string $lang) ### Parameters - **$lang** (string) - Required - The locale to set. ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->language('es') ``` ``` -------------------------------- ### Use custom form request in a route Source: https://github.com/laragear/turnstile/blob/2.x/README.md Use the custom `CommentStoreRequest` in a route closure. The validated data is retrieved with `$request->validated()`, and the Turnstile token is not included in the validated data. ```php use App\Models\Comment; use Illuminate\Support\Facades\Route; use App\Http\Requests\CommentStoreRequest; Route::post('comment', function (CommentStoreRequest $request) { return Comment::create($request->validated()); }) ``` -------------------------------- ### Widget component in a form Source: https://github.com/laragear/turnstile/blob/2.x/README.md Add the Turnstile widget to your forms using the component. The widget may render as usual or be invisible depending on the Widget Mode. ```blade
@csrf ``` -------------------------------- ### Override turnstileToken() for custom challenge key Source: https://github.com/laragear/turnstile/blob/2.x/README.md Override the turnstileToken() method to retrieve the token from a custom form field when using a custom challenge key. ```php public array $data = []; /** * Return token for the Turnstile Challenge present in the form. */ protected function turnstileToken(): ?string { return $this->data['cloudflare-turnstile-token']; } ``` -------------------------------- ### TurnstileWidget::withoutScript() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Disables the automatic injection of the Turnstile script. ```APIDOC ## TurnstileWidget::withoutScript() ### Description Disables the automatic injection of the Turnstile script. ### Method withoutScript() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->withoutScript() ``` ``` -------------------------------- ### Turnstile::failed() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Checks if the retrieved Turnstile Challenge has failed. Must be invoked after the challenge has been retrieved. ```APIDOC ## Turnstile::failed() ### Description Checks if the retrieved Turnstile Challenge has failed. Must be invoked after the challenge has been retrieved. ### Method `failed()` ### Parameters None ### Return Value - **bool** - `true` if the challenge failed, `false` otherwise. ### Example ```php use Laragear\Turnstile\Facades\Turnstile; if (Turnstile::failed()) { // Challenge failed } ``` ``` -------------------------------- ### Override skipChallengeWhenPrecognitive for precognitive requests Source: https://github.com/laragear/turnstile/blob/2.x/README.md Override `skipChallengeWhenPrecognitive()` to control whether the Turnstile Challenge is skipped on precognitive requests. The default behavior skips the challenge on precognitive requests to avoid disrupting live validation. ```php namespace App\Http\Requests; use Laragear\Turnstile\Http\Requests\TurnstileRequest; class CommentStoreRequest extends TurnstileRequest { protected function skipChallengeWhenPrecognitive(): bool { return $this->hasHeader('Requires-CF-Turnstile-Challenge'); } // ... } ``` -------------------------------- ### Use InteractsWithTurnstile trait in Livewire component Source: https://github.com/laragear/turnstile/blob/2.x/README.md Add the trait to a Livewire component to automatically validate the Turnstile challenge when all validation rules pass. The trait overrides the validate() method. ```php use App\Models\Ball; use Laragear\Turnstile\Livewire\InteractsWithTurnstile; use Livewire\Attributes\Rule; use Livewire\Component; class MyCustomPage extends Component { use InteractsWithTurnstile; #[Rule('required')] public $name; #[Rule('required')] public $color; public function save() : Schema { $data = $this->validate(); Ball::create($data); } } ``` -------------------------------- ### Turnstile::hasChallenge() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Checks if a Turnstile Challenge has been received and saved in the Application Container. Use this method to verify the presence of a challenge before retrieving it. ```APIDOC ## Turnstile::hasChallenge() ### Description Checks if a Turnstile Challenge has been received and saved in the Application Container. ### Method `hasChallenge()` ### Parameters None ### Return Value - **bool** - `true` if a challenge exists, `false` otherwise. ### Example ```php use Laragear\Turnstile\Facades\Turnstile; if (Turnstile::hasChallenge()) { // Challenge exists } ``` ``` -------------------------------- ### Bypass rule when authenticated with turnstile:auth Source: https://github.com/laragear/turnstile/blob/2.x/README.md Set the `auth` parameter on the rule to bypass the check if the user is authenticated. ```php use Illuminate\Http\Request; use Laragear\Turnstile\Facades\Turnstile; public function create(Request $request) { $request->validate([ Turnstile::key() => 'turnstile:auth', ]); // ... } ``` -------------------------------- ### TurnstileWidget::appearanceInteractionOnly() Source: https://github.com/laragear/turnstile/blob/2.x/README.md Sets the appearance of the widget to appear only when required. ```APIDOC ## TurnstileWidget::appearanceInteractionOnly() ### Description Sets the appearance of the widget to appear only when required. ### Method appearanceInteractionOnly() ### Parameters None ### Return Value TurnstileWidget instance ### Example ```php TurnstileWidget::make()->appearanceInteractionOnly() ``` ```