How to Integrate Google reCAPTCHA v3 in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to integrate google reCAPTCHA v3 in laravel.

 

How to integrate google reCAPTCHA v3 in laravel

Integrating Google reCAPTCHA v3 in Laravel is a straightforward process that involves a few steps.

Let's follow these steps:

 

Step 1 - Create a Google reCAPTCHA v3 account and generate site and secret keys from the reCAPTCHA dashboard.

 

Step 2 - Install the Google reCAPTCHA package for Laravel by this command in your project directory:

composer require google/recaptcha "^1.0"

 

Step 3 -  Add your site and secret keys to the `.env` file of your Laravel project:

RECAPTCHA_SITE_KEY=your_site_key_here
RECAPTCHA_SECRET_KEY=your_secret_key_here

 

Step 4 -  Create a form where you want to add the reCAPTCHA validation.

Add the following code inside the form for reCaptcha:

<input type="hidden" name="recaptcha_response" id="recaptchaResponse">

 

Step 5 -  Add the following script tag to the head section:

<script src="https://www.google.com/recaptcha/api.js?render=your_site_key_here"></script>

 

Step 6 -  Add the following JavaScript code to the form page or layout file:

<script>
    grecaptcha.ready(function() {
        grecaptcha.execute('your_site_key_here', {action: 'submit'}).then(function(token) {
            document.getElementById('recaptchaResponse').value = token;
        });
    });
</script>

 

Step 7 -  In your Laravel controller, validate the reCAPTCHA response using the `Validator` facade:

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

public function submitForm(Request $request)
{
    $validator = Validator::make($request->all(), [
        'recaptcha_response' => 'required|recaptcha',
    ]);

    if ($validator->fails()) {
        // Handle validation errors
    }

    // Process form data
}

Note: the `recaptcha` rule is added to the validation rules array.

 

Step 8 -  Finally, run your Laravel project and test the form to make sure that the reCAPTCHA validation is working.

 

That's it! You have successfully integrated Google reCAPTCHA v3 in your Laravel project.

Comments 0

Leave a comment