LaravelでCloudFlareを導入してみる

2025.08.29 09:00
2025.09.02 09:26
LaravelでCloudFlareを導入してみる

Laravelにおいて、Google reCAPTCHA の代わりに Cloudflare Turnstile を使う方法をまとめました。シンプルに置き換えられて、無料で使えるのもありがたいところです。

事前準備としてCloudFlareでキーを発行しておきます。やりかたは以前書いた記事を参考にしてみて下さい。

GoogleのreCAPTCHAからCloudFlareに乗り換える

1. 導入方法

1-1. Laravel 側にパッケージ導入

docker compose exec php composer require anhskohbo/no-captcha

1-2. .env にキーを設定

CLOUDFLARE_SITEKEY=your_site_key
CLOUDFLARE_SECRET=your_secret_key

1-3. config/services.php に追加

'turnstile' => [
    'enabled' => env('TURNSTILE_ENABLED', false),
    'sitekey' => env('TURNSTILE_SITEKEY'),
    'secret'  => env('TURNSTILE_SECRET'),
],

1-4. フォーム

<form method="POST" action="{{ route('contact.store') }}">
    @csrf

    <!-- フォーム要素 -->

    <div class="cf-turnstile" data-sitekey="{{ config('services.turnstile.sitekey') }}"></div>

    <button type="submit">送信</button>
</form>

<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>

1-5. FormRequest

use Illuminate\Support\Facades\Http;

public function rules(): array
{
    return [
        'cf-turnstile-response' => ['required', function ($attribute, $value, $fail) {
            $response = Http::asForm()->post(
                'https://challenges.cloudflare.com/turnstile/v0/siteverify',
                [
                    'secret'   => config('services.turnstile.secret'),
                    'response' => $value,
                    'remoteip' => request()->ip(),
                ]
            );

            if (!($response->json('success'))) {
                $fail('Bot 検証に失敗しました。');
            }
        }],
    ];
}

2. ローカルやテストの対応

テスト環境では Turnstile を無効化することもできます。
.env の設定で切り替え可能です。

TURNSTILE_ENABLED=false

Blade 側では以下のように条件分岐を入れておくと便利です。

@if(config('services.turnstile.enabled'))
  <div class="cf-turnstile" data-sitekey="{{ config('services.turnstile.sitekey') }}"></div>
@endif

まとめ

Cloudflare Turnstile は、Google reCAPTCHA の代替としてとても簡単に導入できます。環境変数とサービス設定を分けておけば、本番とテストでの切り替えもスムーズですし、検証処理も FormRequest にまとめて実装しておけばシンプルに運用できます。

今回は以上です!