Laravel & Php

How to setup Google reCAPTCHA V2 and V3 with Laravel


If you prefer not to use a package, you can manually integrate Google reCAPTCHA into your Laravel application. Below are the steps:

1. Add Site and Secret Keys to .env

In your .env file, add the following:

RECAPTCHA_SITE_KEY=your-site-key
RECAPTCHA_SECRET_KEY=your-secret-key

Replace your-site-key and your-secret-key with the values from the Google reCAPTCHA admin console.

2. Update the HTML Form

In your Blade file where you want to include the reCAPTCHA widget, add the following:

For reCAPTCHA v2 (checkbox):

<form method="POST" action="{{ route('your.route.name') }}">
    @csrf
    <!-- Your form inputs here -->
    
    <div class="g-recaptcha" data-sitekey="{{ env('RECAPTCHA_SITE_KEY') }}"></div>
    
    <button type="submit">Submit</button>
</form>

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

For reCAPTCHA v3 (invisible):

<script src="https://www.google.com/recaptcha/api.js?render={{ env('RECAPTCHA_SITE_KEY') }}"></script>

<form method="POST" action="{{ route('your.route.name') }}" id="your-form-id">
    @csrf
    <!-- Your form inputs here -->
    
    <input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response">
    <button type="submit">Submit</button>
</form>

<script>
    grecaptcha.ready(function() {
        grecaptcha.execute('{{ env('RECAPTCHA_SITE_KEY') }}', { action: 'submit' }).then(function(token) {
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>

3. Validate reCAPTCHA on the Server

In your Controller, verify the reCAPTCHA response:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

public function yourFormHandler(Request $request)
{
    $recaptchaResponse = $request->input('g-recaptcha-response');
    $secretKey = env('RECAPTCHA_SECRET_KEY');

    // Verify reCAPTCHA response
    $response = Http::asForm()->post('https://www.google.com/recaptcha/api/siteverify', [
        'secret' => $secretKey,
        'response' => $recaptchaResponse,
        'remoteip' => $request->ip(),
    ]);

    $responseData = $response->json();

    if (!$responseData['success'] || $responseData['score'] < 0.5) { // Adjust 'score' threshold for v3
        return back()->withErrors(['captcha' => 'Captcha verification failed. Please try again.']);
    }

    // Proceed with form handling logic
    // ...
}

4. Handle Validation Errors in the Blade Template

In your Blade file, display validation errors:

@if ($errors->has('captcha'))
    <div class="alert alert-danger">{{ $errors->first('captcha') }}</div>
@endif

Notes:

  • For reCAPTCHA v2, the success key in the response is sufficient.
  • For reCAPTCHA v3, the score indicates the likelihood of the request being human. You can adjust the threshold (e.g., 0.5).

This approach does not rely on any external Laravel packages and uses only Google’s reCAPTCHA API.


Laravel PHP
Share with Friends

Like this chef? Share with friends..