Laravel 12 - Integrate reCAPTCHA v3 with Livewire Auth.

Touseef Afridi
07 Nov 25

Laravel 12 - Integrate reCAPTCHA v3 with Livewire Auth.

In this guide, you’ll learn how to integrate Google reCAPTCHA v3 with Laravel 12 Livewire authentication to secure your login and registration forms, validate tokens, and block bots without affecting user experience.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

This guide walks you through integrating Google reCAPTCHA v3 into a Laravel 12 project with Livewire authentication. It covers creating a fresh Laravel project, installing the reCAPTCHA package, and configuring the Site Key and Secret in your .env file. You’ll learn how to initialize reCAPTCHA v3 on your authentication pages, including login and registration forms, add the hidden reCAPTCHA field, and validate user responses on the backend. The guide also demonstrates how to inspect the reCAPTCHA score and implement optional logic for additional security. Following these steps helps protect your authentication forms from bots and spam, ensuring a safer and smoother experience for your users.

Step # 1 : Create a New Laravel Project with Livewire Authentication.

Start by creating a new Laravel 12 project. If you have Laravel installed globally, run the following command in your terminal.
laravel new reCAPTCHAV3
Alternatively, if Laravel isn’t installed globally, you can create the project using Composer.
composer create-project laravel/laravel --prefer-dist reCAPTCHAV3
When using Composer, the setup runs automatically, no interactive prompts will appear, so you’ll need to configure everything manually later. When using the Laravel Installer, you’ll go through a short interactive setup. Choose the following options when prompted.
  • Would you like to install the starter kit? — Choose Livewire.
  • Which authentication provider do you prefer? [Laravel's built-in authentication]? — Choose Laravel.
  • Would you like to use Laravel Volt? (yes/no)? — Choose No.
  • After selecting None, you'll be asked about testing framework. — Choose Pest.
  • Frontend Dependencies: When prompted, type yes to install them automatically

You now have a Laravel 12 project named reCAPTCHAV3 fully set up with Livewire authentication.

Step # 2 : Access the project.

Open your terminal (for example, Git Bash, Command Prompt, or VS Code Terminal) and navigate to your Laravel project directory using the following command.
cd c:xampp/htdocs/reCAPTCHAV3
This command takes you inside your Laravel project folder, where you can run artisan commands and manage your application files.

Step # 3 : Install the reCAPTCHA V3 Package.

Next, install the reCAPTCHA v3 package by running the following command in your project directory.
composer require josiasmontag/laravel-recaptchav3
This command will download the package and automatically update your composer.json file with the required dependencies.

Step # 4 : Publish the Configuration File.

Run the following command to publish the package’s configuration file.
php artisan vendor:publish --provider="Lunaweb\RecaptchaV3\Providers\RecaptchaV3ServiceProvider"
This will copy the reCAPTCHA v3 configuration file into your project’s config directory, allowing you to customize its settings if needed.

Step # 5 : Obtain reCAPTCHA v3 Site Key and Secret.

To use reCAPTCHA v3, you need to get the 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. Log in with your Google account, or sign up if you don’t have one yet.
  3. Create a label for your site to easily identify your keys later.
  4. Select reCAPTCHA v3 as the version.
  5. Add your site’s domain(s) to ensure security. Since we are working on localhost, you can use 127.0.0.1 as your domain.
  6. Click Submit to generate your Site Key and Secret Key.


After submitting, you’ll be taken to a page where both your Site Key and Secret Key are displayed.

Next, open the .env file in your Laravel project and add the keys like this.
RECAPTCHAV3_SITEKEY="Define your SITE KEY here"
RECAPTCHAV3_SECRET="Define your SITE SECRET here"
Replace "Your Site Key here" and "Your Secret Key here" with the keys you just generated. This links your Laravel app with Google’s reCAPTCHA service.

Step # 6 : Initialize reCAPTCHA V3 JavaScript.

Open resources/views/layouts/auth/simple.blade.php and add the following inside the <head> section.
<!-- Initialize reCAPTCHA V3 -->
{!! RecaptchaV3::initJs() !!}
This ensures the reCAPTCHA V3 JavaScript loads early enough for all forms in this layout, allowing the hidden token to be generated correctly when the form is submitted.

Step # 7 : Add reCAPTCHA Field to the Registration Form.

Open your register.blade.php file and locate the Create account submit button inside your form. Add the following above the submit button.
{{-- Hidden input for reCAPTCHA V3 --}}
{!! RecaptchaV3::field('register') !!}
<div class="flex items-center justify-end">
    <flux:button type="submit" variant="primary" class="w-full">
        {{ __('Create account') }}
    </flux:button>
</div>
This will include a hidden reCAPTCHA input in your form, so the reCAPTCHA score can be validated in the background when the form is submitted. If you want to do it for the login form as well, don’t forget to add the respective field in the login form.

Step # 8 : Validate reCAPTCHA in the CreateNewUser Action.

Open app/Actions/Fortify/CreateNewUser.php. In the create() method, add the reCAPTCHA validation along with the existing fields.
'g-recaptcha-response' => 'required|recaptchav3:register,0.5',
This validates the reCAPTCHA response with a minimum score of 0.5 before registration proceeds. Make sure the action name 'register' here matches the one defined in your form.

Step # 9 : Verify reCAPTCHA Integration.

Let's run the project using the following command.
php artisan serve
Navigate to the Register page in your browser. Use the developer tools to check that a hidden input named g-recaptcha-response is present. This field is automatically generated by reCAPTCHA V3 and will be included when the form is submitted.

To inspect the submitted data, temporarily add a dd() at the start of the create() method in app/Actions/Fortify/CreateNewUser.php.
<?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\CreatesNewUsers;
class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;
    /**
     * Validate and create a newly registered user.
     *
     * @param array<string, string> $input
     */
    public function create(array $input): User
    {
        // View all form data, including the reCAPTCHA token
        dd($input);
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique(User::class),
            ],
            'password' => $this->passwordRules(),
            // Validate the reCAPTCHA v3 response with a minimum score of 0.5
            'g-recaptcha-response' => 'required|recaptchav3:register,0.5',
        ])->validate();
        return User::create([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => $input['password'],
        ]);
    }
}
Submit the form, and the dd($input) will display all incoming data, including the reCAPTCHA token. This confirms that reCAPTCHA is correctly integrated and functioning.

Once verified, remove the dd() so that registration works normally.

Step # 10 : Example of Validation Based on reCAPTCHA Score (Optional).

You can use the Lunaweb\RecaptchaV3\Facades\RecaptchaV3 facade to implement custom logic depending on the reCAPTCHA score. For Fortify, this can be done in the create() method of app/Actions/Fortify/CreateNewUser.php.
<?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Laravel\Fortify\Contracts\CreatesNewUsers;
// Facade for verifying reCAPTCHA v3 tokens and retrieving scores
use Lunaweb\RecaptchaV3\Facades\RecaptchaV3;
class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules;
    /**
     * Validate and create a newly registered user.
     *
     * @param array<string, string> $input
     */
    public function create(array $input): User
    {
        // Get reCAPTCHA score
        $score = RecaptchaV3::verify($input['g-recaptcha-response'], 'register');
        // // Inspect score with dd()
        if ($score > 0.5) {
            dd($score, 'Score OK – continue registration');
        } else {
            dd($score, 'Score too low – block registration');
        }
        // Validate user input including reCAPTCHA
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique(User::class)],
            'password' => $this->passwordRules(),
            // The reCAPTCHA token is required; the score is verified manually with RecaptchaV3::verify()
            'g-recaptcha-response' => 'required',
        ])->validate();
        return User::create([
            'name' => $input['name'],
            'email' => $input['email'],
            'password' => $input['password'],
        ]);
    }
}
RecaptchaV3::verify() retrieves the reCAPTCHA score for the 'register' action. In this example, dd() is used to inspect the score so you can see its value. You can then implement your own logic such as allowing, blocking, or flagging registrations based on the reCAPTCHA score.

Conclusion

By following this guide, you've successfully integrated Google reCAPTCHA V3 into your Laravel 12 project with Livewire authentication, strengthening your registration form against bots and spam. With reCAPTCHA V3 in place, your application is now more secure, and you can easily apply the same setup to other forms. This straightforward integration ensures both security and a smooth, seamless experience for your users.
For more details, check the josiasmontag/laravel-recaptchav3 package 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