Laravel 12 - How to Integrate Google reCAPTCHA v2 with Livewire Auth.

Touseef Afridi
14 Nov 25

Laravel 12 - How to Integrate Google reCAPTCHA v2 with Livewire Auth.

In this tutorial, we will learn how to integrate Google reCAPTCHA v2 in Laravel 12 with Livewire Auth to secure the registration form, prevent bots from creating fake accounts, and ensure only real users can sign up safely.

Quick Overview

This guide walks you through integrating Google reCAPTCHA V2 into a Laravel 12 project with Livewire authentication. You’ll set up a fresh Laravel project, install and configure the reCAPTCHA package, obtain your Site Key and Secret Key from Google, add the reCAPTCHA widget to the registration form, and validate that the user completes the “I’m not a robot” verification during registration. Finally, you’ll test the form to ensure the reCAPTCHA is working correctly and displaying errors if the verification is not completed, providing a secure and fully functional registration process.

Step # 1 : Set Up a New Laravel 12 Project with Livewire Authentication.

Start by creating a fresh Laravel 12 project. If Laravel is installed globally, run
laravel new reCAPTCHAV2
If you dont have Laravel installed globally, you can create the project using Composer.
composer create-project laravel/laravel --prefer-dist reCAPTCHAV2
When using Composer, the setup runs automatically with no interactive prompts, so you’ll need to configure authentication, testing, and frontend dependencies manually later. When using the Laravel Installer, you’ll go through a short interactive setup. Choose the following options when prompted.
  • Starter Kit: Select Livewire to enable Livewire based authentication.
  • Authentication Provider: Choose Laravel’s built-in authentication for simplicity.
  • Laravel Volt: Select No, as it’s not required for this project.
  • Testing Framework: Pick Pest as the testing framework.
  • Frontend Dependencies: Type Yes to install them automatically.

This will set up a fresh Laravel project with Livewire authentication, Pest for testing, SQLite as the default database, and all the default migrations ready to go.

Step # 2 : Access the project.

Open a terminal (for example, Git Bash) and navigate to the root folder of your Laravel project using.
cd c:xampp/htdocs/reCAPTCHAV2
This will take you to your project’s root directory, where you can start configuring your application and continue with the setup.

Step # 3 : Install the reCAPTCHA V2 Package.

To integrate Google reCAPTCHA V2 into your Laravel application, run the following command in your project’s root directory.
composer require anhskohbo/no-captcha
This will download and install the package, providing all the necessary tools to easily add Google reCAPTCHA V2 protection to your forms.

Step # 4 : Publish the Configuration File (Optional).

If you want to customize reCAPTCHA settings, run the following command to publish its config file.
php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"
This will create a configuration file at config/captcha.php, where you can adjust reCAPTCHA options such as site key, secret key, and other settings as needed.

Step # 5 : Get Your reCAPTCHA V2 Site Key and Secret Key.

To use reCAPTCHA V2 in your Laravel application, you first need to obtain a Site Key and Secret Key from Google’s reCAPTCHA Admin Console.
  1. Go to the reCAPTCHA Admin Console (Link : https://www.google.com/recaptcha/admin/create).
  2. Sign in with your Google account, or create one if you don’t have it yet.
  3. Enter a label for your site. This helps you identify your keys later.
  4. Select reCAPTCHA v2, then choose the “I’m not a robot” checkbox option.
  5. Add your website’s domain(s) to restrict the keys to your site. For local development, you can use 127.0.0.1.
  6. Click Submit to generate the keys.


Once submitted, you’ll be taken to a page showing both your Site Key and Secret Key.

Next, open your Laravel project’s .env file and add the keys like this.
NOCAPTCHA_SITEKEY="your-site-key"
NOCAPTCHA_SECRET="your-secret-key"
Replace your-site-key and your-secret-key with the keys you just generated. This links your Laravel application to Google’s reCAPTCHA service, enabling it to verify users.

Step # 6 : Add reCAPTCHA V2 to the Registration Form.

Open resources/views/layouts/auth/simple.blade.php and add the following inside the <head> section.
<!-- Render the necessary JavaScript for the reCAPTCHA widget -->
{!! NoCaptcha::renderJs() !!}
This ensures the required reCAPTCHA script is loaded on all authentication pages.
Next, Open your registration Blade file (resources/views/auth/register.blade.php) and inside the <form>, add the following just before the Create Account button.
<!-- reCAPTCHA V2 Widget -->
<div class="mt-4">
<!-- Display the reCAPTCHA V2 widget -->
{!! NoCaptcha::display() !!}
<!-- Display validation error message for the reCAPTCHA V2 response -->
@error('g-recaptcha-response')
<p class="text-red-500 text-sm mt-1">
{{ $message }}
</p>
@enderror
</div>
This will render the reCAPTCHA widget on the form and display any validation error messages related to the response.

Step # 7 : Validate reCAPTCHA v2.

To ensure that users complete the reCAPTCHA when registering, you need to add validation for the g-recaptcha-response field. Open CreateNewUser.php and update the create method as follows.
<?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\CreatesNewUsers;
// Import the facade to validate the reCAPTCHA V2 response in the registration process
use Anhskohbo\NoCaptcha\Facades\NoCaptcha;
class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;
    /**
     * Validate and create a newly registered user.
     *
     * @param array<string, string> $input
     */
    public function create(array $input): User
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique(User::class),
            ],
            'password' => $this->passwordRules(),
            // Validate the reCAPTCHA response to ensure it is present and valid
            'g-recaptcha-response' => 'required|captcha',
        ])->validate();
        return User::create([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => $input['password'],
        ]);
    }
}
The validation rule 'g-recaptcha-response' => 'required|captcha' ensures that users successfully complete the reCAPTCHA v2 “I’m not a robot” verification before submitting the registration form. If the user does not check the box or if the verification fails, the registration will be rejected and an error message will be displayed. Note that reCAPTCHA v2 may sometimes show an additional image challenge only when Google’s risk analysis detects suspicious activity.

Step # 8 : Test the reCAPTCHA V2 Integration.

With everything set up, you can now run your Laravel project and test the registration form. Start the development server by running.
php artisan serve
Once the server is running, open your browser and go to the registration page at http://127.0.0.1:8000/register. You should now see the reCAPTCHA widget displayed on the registration form. Try submitting the form without checking the “I’m not a robot” checkbox, an error message should appear, indicating that the reCAPTCHA validation has failed.


Next, check the “I’m not a robot” box and submit the form again. This time, the validation should pass, and you’ll be redirected to the dashboard.


This simple test confirms that reCAPTCHA is correctly integrated and working during registration. Once verified, you can continue with any further customizations or adjustments to your form or validation logic.

Conclusion

By following this guide, you've successfully integrated Google reCAPTCHA V2 into your Laravel 12 project with Livewire authentication. This setup ensures that your registration form is protected from bots and spam, improving the security of your application. With the reCAPTCHA widget added to the form and properly validated during registration, your Laravel project now has an effective mechanism to prevent automated submissions. You can easily extend this protection to other forms within your application as needed. This simple yet powerful integration enhances both security and user experience.
For more details, be sure to refer to the anhskohbo/no-captchapackage documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering