Laravel CAPTCHA Integration
This recipe shows how to integrate TrustCaptcha into a Laravel application. The frontend setup is the same as for any other PHP application — this page focuses on the server-side validation.
The setup section gets you to a working integration in three small steps using a controller method directly. Below it, an optional refactor section shows the more reusable Laravel-idiomatic approach (Form Request + custom rule).
Preparation
Section titled “Preparation”You should have already completed the following steps before you wire TrustCaptcha into your Laravel application.
Read Get-Started: Get a quick overview of the concepts behind TrustCaptcha and the integration process in get started.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
1. Embed the frontend widget
Section titled “1. Embed the frontend widget”First, add the TrustCaptcha script to your page (see the JavaScript Guide for version pinning and self-hosting options).
Then place the <trustcaptcha-component> element inside your Blade form. The widget appends a hidden tc-verification-token field on submit, which your Laravel controller receives in $request like any other form input.
<script type="module" src="https://cdn.trustcomponent.com/trustcaptcha/3.0.x/trustcaptcha.esm.min.js"></script>
<form method="POST" action="{{ route('contact.submit') }}"> @csrf
<label>Email</label> <input type="email" name="email" required>
<trustcaptcha-component sitekey="<your_site_key>"></trustcaptcha-component>
<button type="submit">Send</button></form>See the Widget Overview for the full property reference.
2. Install the PHP SDK
Section titled “2. Install the PHP SDK”composer require trustcomponent/trustcaptcha-php:^3.03. Validate the token in your controller
Section titled “3. Validate the token in your controller”<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;use TrustComponent\TrustCaptcha\TrustCaptcha;
class ContactController extends Controller{ public function submit(Request $request) { $apiKey = '<your_api_key>'; // In production, load from env: config('services.trustcaptcha.api_key') $token = $request->input('tc-verification-token');
try { $trustCaptcha = new TrustCaptcha($apiKey); $result = $trustCaptcha->getVerificationResult($token); } catch (\Throwable $e) { return back()->withErrors(['captcha' => 'CAPTCHA verification failed.']); }
if (!$result->verificationPassed || $result->score > 0.5) { return back()->withErrors(['captcha' => 'CAPTCHA verification failed.']); }
// CAPTCHA passed — request data is safe to use. // ... your business logic ...
return back()->with('status', 'Thanks!'); }}That’s it — the form is now protected. For real deployments, move the API key out of the source code (see the comment) and consider explicit failover handling — see Failover Behavior for the reasoning and a code template.
Refactor: extract to a Form Request rule
Section titled “Refactor: extract to a Form Request rule”If you protect more than one route, the most idiomatic Laravel approach is a custom validation rule combined with a Form Request. The verification call then runs automatically as part of Laravel’s normal validation pipeline, and validation failures land in $errors like any other rule.
Configure the API key
Section titled “Configure the API key”TRUSTCAPTCHA_API_KEY=<your_api_key>'trustcaptcha' => [ 'api_key' => env('TRUSTCAPTCHA_API_KEY'),],Create the rule
Section titled “Create the rule”php artisan make:rule TrustCaptchaToken<?php
namespace App\Rules;
use Closure;use Illuminate\Contracts\Validation\ValidationRule;use TrustComponent\TrustCaptcha\TrustCaptcha;
class TrustCaptchaToken implements ValidationRule{ public function validate(string $attribute, mixed $value, Closure $fail): void { if (empty($value)) { $fail('CAPTCHA verification token missing.'); return; }
try { $trustCaptcha = new TrustCaptcha(config('services.trustcaptcha.api_key')); $result = $trustCaptcha->getVerificationResult($value);
if (!$result->verificationPassed || $result->score > 0.5) { $fail('CAPTCHA verification failed.'); } } catch (\Throwable $e) { $fail('CAPTCHA verification failed.'); } }}Use the rule in a Form Request
Section titled “Use the rule in a Form Request”php artisan make:request ContactRequest<?php
namespace App\Http\Requests;
use App\Rules\TrustCaptchaToken;use Illuminate\Foundation\Http\FormRequest;
class ContactRequest extends FormRequest{ public function authorize(): bool { return true; }
public function rules(): array { return [ 'email' => ['required', 'email'], 'tc-verification-token' => ['required', 'string', new TrustCaptchaToken()], ]; }}Type-hint the ContactRequest in your controller method and Laravel will run the validator automatically — no manual call needed:
public function submit(ContactRequest $request) { /* CAPTCHA already validated */ }CSRF. Laravel’s CSRF protection (@csrf) and TrustCaptcha are independent layers — both should stay enabled. The CAPTCHA token does not replace the CSRF token.
Field name. The default token field name contains a dash (tc-verification-token). Laravel accepts dashed input names in validation rules and $request->input('tc-verification-token'). If you’d rather use camelCase, set token-field-name="trustcaptchaToken" on the widget and adapt the form / rule code.
Configured SDK options. For custom timeouts, proxy, or a custom API host, pass them as the second constructor argument: new TrustCaptcha($apiKey, ['apiHost' => ..., 'proxy' => ...]). See the PHP Guide for the full constructor options.
Next steps
Section titled “Next steps”Once you have wired TrustCaptcha into your Laravel application, you can use TrustCaptcha to its full extent. However, we still recommend the following additional technical and organizational measures:
Security rules: You can find many security settings for your CAPTCHA in the CAPTCHA settings. These include, for example, authorized websites, CAPTCHA bypass for specific IP addresses, bypass keys, IP based blocking, geoblocking, individual difficulty and duration of the CAPTCHA, and much more. Learn more about the security rules.
Privacy & GDPR compliance: Include a passage in your privacy policy that refers to the use of TrustCaptcha. We also recommend that you enter into a data processing agreement with us to stay GDPR-compliant. Learn more about data protection.
Accessibility & UX: Customize TrustCaptcha to your website so that your website is as accessible as possible and offers the best possible user experience. More about accessibility.
Failover behavior: Decide how your backend should behave when our service is temporarily unreachable. This is particularly important for high-availability flows where blocking real users during an outage is worse than letting through a small amount of unverified traffic. Learn more about failover behavior.
Testing: If you use automated testing, make sure that the CAPTCHA does not block it. Learn more about testing.