Laravel 13 - How to Integrate Google reCAPTCHA v2 with Livewire.

Touseef Afridi
18 Aug 26

Laravel 13 - How to Integrate Google reCAPTCHA v2 with Livewire.

In this tutorial, we will learn how to integrate Google reCAPTCHA v2 with Laravel 13 and Livewire authentication to protect registration forms from bots and spam using checkbox verification and server-side validation.

Quick Overview

This guide walks you through integrating Google reCAPTCHA v2 into a Laravel 13 application with Livewire authentication. It starts by creating a fresh Laravel project, followed by installing and configuring the anhskohbo/no-captcha package. You’ll then learn how to generate your Google reCAPTCHA credentials, add the reCAPTCHA v2 checkbox to the registration form, and validate the submitted response on the backend. Finally, the tutorial shows you how to test the integration by checking both successful and failed registration attempts. By following these steps, you can add an extra layer of protection to your registration form and help prevent automated submissions and spam.

Step # 1 : Create a Fresh Laravel 13 Application with Livewire Authentication.

For this tutorial, we'll begin by creating a new Laravel 13 application named reCAPTCHAV2 and configure it with Livewire authentication. Before creating the project, make sure Composer is installed on your system, as it is required for handling Laravel's PHP dependencies. It's also helpful to have the Laravel Installer installed globally. If it isn't available on your system yet, install it using.
composer global require laravel/installer
Once the Installer has been configured, create the Laravel application with the following command.
laravel new reCAPTCHAV2
While creating the project, Laravel will ask you to select a few configuration options. Use the following choices to proceed.
  • Starter Kit: Select Yes to use a starter kit.
  • Kit: Select Livewire so the application uses Livewire for its components.
  • Authentication Provider: Select Laravel's built-in authentication to include the standard registration and login functionality.
  • Single-file Livewire Components: Choose Yes to keep the component's PHP logic and view in the same file.
  • Teams Support: Select No, as team functionality isn't needed for this application.
  • Authentication Features: Select Registration, as we only need user registration functionality for now.
  • Boost Features: Hit Enter to select none, as Boost features aren't required for this application.
  • Third-party AI Guidelines/Skills: Hit Enter to select none, as no third-party AI guidelines or skills are required for this application.
  • Boost Integrations: Hit Enter to select none, as no Boost integrations are required for this application.
  • AI Agents: Select Amp as the AI agent for this application.

Once the installation process finishes, the reCAPTCHAV2 project will be ready with Laravel 13, Livewire, and registration authentication configured. No Boost features, third-party AI guidelines/skills, or Boost integrations will be enabled, while Amp will be configured as the AI agent. We can then move on to the next step.

Step # 2: Navigate to the reCAPTCHAV2 Project.

With the Laravel application created, open your preferred terminal and navigate to the reCAPTCHAV2 project directory. You can use PowerShell, Command Prompt, Git Bash, or the built-in terminal in VS Code. Use the appropriate command format for your selected terminal.
PowerShell:
cd C:\xampp\htdocs\reCAPTCHAV2
Command Prompt (CMD):
cd C:\xampp\htdocs\reCAPTCHAV2
Git Bash:
cd /c/xampp/htdocs/reCAPTCHAV2
Once you're inside the project directory, you can continue running the required Artisan commands for the application setup.

Step # 3 : Add the reCAPTCHA V2 Package to Laravel.

Now, install the package that will handle Google reCAPTCHA V2 integration in Laravel. For this tutorial, we'll use the anhskohbo/no-captcha package. It provides Laravel-friendly helpers and validation support for adding reCAPTCHA to application forms. Instead of handling the Google reCAPTCHA API integration manually, the package makes it easier to display the CAPTCHA widget and verify the submitted response on the server. Install the package from your project root with.
composer require anhskohbo/no-captcha
Composer will download and register the package with your Laravel application, making its reCAPTCHA helpers and validation features available for use.

Step # 4 : Publish the reCAPTCHA V2 Configuration.

If you need to manage the package settings through Laravel's configuration files, you can publish the package configuration using the following Artisan command.
php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"
After running the command, Laravel will add the package configuration file to your project. This gives you a central place to manage settings such as the site key, secret key, and other reCAPTCHA options.

Step # 5 : Generate Google reCAPTCHA V2 Credentials.

Before adding reCAPTCHA to your Laravel application, you first need to generate a Site Key and Secret Key through Google’s reCAPTCHA Admin Console. These credentials will be used to establish the connection between your Laravel project and Google reCAPTCHA. Follow the steps below to get these keys.
  1. Go to the reCAPTCHA Admin Console : https://www.google.com/recaptcha/admin/create

  2. Log in using your Google account. If you don’t have an account, you can create one before continuing.

  3. Enter a suitable label for your website so you can recognize the project easily in the future.

  4. Under the reCAPTCHA type, select reCAPTCHA v2, and then choose the “I’m not a robot” Checkbox option.

  5. Enter your website domain in the domain field. For a Laravel project running on your local machine, you can add 127.0.0.1.

  6. Click Submit to register the site and generate the required reCAPTCHA keys.

Once the registration is completed, Google will provide you with both the Site Key and Secret Key on the following page. Keep these values handy, as they will be added to your Laravel configuration.

Next, open the .env file located in your Laravel project and add the following entries.
NOCAPTCHA_SITEKEY="your-site-key"
NOCAPTCHA_SECRET="your-secret-key"
Replace your-site-key and your-secret-key with the credentials generated. These values allow your Laravel application to communicate with Google’s reCAPTCHA service and validate the submitted requests.

Step # 6 : Integrate Google reCAPTCHA V2 into the Registration Form.

Now that we have the reCAPTCHA keys, let’s add the reCAPTCHA V2 widget to the registration form. Open resources/views/pages/auth/register.blade.php and add the following code to load the JavaScript required by the reCAPTCHA widget.
<!-- Load the required JavaScript for reCAPTCHA V2--> 
{!! NoCaptcha::renderJs() !!}
This loads the required reCAPTCHA script so the widget can work correctly on the registration page. Next, open your registration Blade file (resources/views/pages/auth/register.blade.php) and inside the <form>, add the following code just before the Create Account button.
<!-- Google reCAPTCHA V2 -->
<div class="mt-4 w-full flex flex-col items-center">
    <!-- Render the reCAPTCHA widget -->
    <div>
        {!! NoCaptcha::display() !!}
    </div>
    <!-- Display the validation error -->
    @error('g-recaptcha-response')
        <p class="text-red-500 text-sm mt-1">
            {{ $message }}
        </p>
    @enderror
</div>
This adds the reCAPTCHA V2 checkbox to the registration form and displays a validation message whenever the submitted reCAPTCHA response is missing or invalid.

Step # 7 : Validate the reCAPTCHA v2 Response.

Now that reCAPTCHA has been added to the registration form, the next step is to validate the response on the server side. In Laravel 13 with Fortify, you can handle this inside CreateNewUser.php, located at: app/Actions/Fortify/CreateNewUser.php. Open the file and update the create method like this.
<?php
namespace App\Actions\Fortify;
use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Laravel\Fortify\Contracts\CreatesNewUsers;
class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules, ProfileValidationRules;
    /**
     * Validate and create a newly registered user.
     *
     * @param array<string, string> $input
     */
    public function create(array $input): User
    {
        Validator::make($input, [
            ...$this->profileRules(),
            'password' => $this->passwordRules(),
            // Validate the submitted reCAPTCHA response
            'g-recaptcha-response' => 'required|captcha',
        ])->validate();
        return User::create([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => $input['password'],
        ]);
    }
}
The 'g-recaptcha-response' => 'required|captcha' rule makes sure that a valid reCAPTCHA response is submitted before the registration process continues. If the user skips the verification or the response fails validation, the registration will be rejected and the corresponding validation error will be shown.
Keep in mind that reCAPTCHA v2 does not always display an image challenge. Google may allow the verification immediately after the checkbox is selected, while an additional challenge can appear when suspicious activity is detected.

Step # 8 : Verify the reCAPTCHA V2 Integration.

Now that everything is configured, it's time to test the reCAPTCHA on the registration form. Start your Laravel development server by running.
php artisan serve
Once the server is running, open http://127.0.0.1:8000/register in your browser. You should see the reCAPTCHA widget 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” checkbox and submit the form again. This time, the reCAPTCHA validation should pass, and you should be redirected to the dashboard.


This quick check ensures that the reCAPTCHA protection is working properly during registration. After confirming everything works as expected, you can move on to any additional changes or improvements to the form and its validation.

Conclusion

By following this guide, you’ve successfully integrated Google reCAPTCHA v2 into your Laravel 13 application with Livewire authentication, adding an extra layer of protection to your registration form against bots and spam. With the reCAPTCHA checkbox and server-side validation in place, you can also apply the same approach to other forms where additional verification is needed. This straightforward integration helps improve security while keeping the registration experience simple for your users.
For more details, refer to the official package documentation: https://github.com/anhskohbo/no-captcha.
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