Laravel 11 - How to Integrate Google reCAPTCHA v2

Touseef Afridi
02 Dec 24

Laravel 11 - How to Integrate Google reCAPTCHA v2

In this tutorial, we’ll see how to integrate Google reCAPTCHA V2 in Laravel 11 to protect your forms from spam while ensuring a smooth user experience.


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


Step # 1 : Create fresh Laravel project with Breeze Auth.

Two commands to create fresh laravel project.
Global Command : laravel new reCAPTCHAV2
Or use
Non Global Command : composer create-project laravel/laravel --prefer-dist reCAPTCHAV2
After running one of the above commands, you'll be prompted.
Would you like to install the starter kit?
Select Breeze.
After selecting Breeze, you'll be asked to choose your stack.
Select Blade.
After selecting Blade, you'll be asked for dark mode support.
Select no.
After selecting No, you'll be asked about testing framework.
Select Pest.
After selecting Pest, you'll be asked to select the database for your application.
Select mysql.
After selecting MySql, you'll be asked if you want to run the default database migration.
Select yes

Step # 2 : Access the project.

Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
Git Bash : cd c:xampp/htdocs/reCAPTCHAV2

Step # 3 : Install reCAPTCHA V2 package.

Run the following command.
Command : composer require anhskohbo/no-captcha

Step # 4 : Publish the Config file (Optional).

Run the following command.
Command : php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"

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

Access Google reCAPTCHA Admin Console. Link : https://www.google.com/recaptcha/admin/create
Sign up or log in to your Google account if you haven't already.
Create a label for your site for identification.
Choose reCAPTCHA v2 as the version and select the "I'm not a robot" checkbox option.
Define your site's domain(s)
Click Submit to generate your Site Key and Secret Key.

You will be redirected to a page where your Site Key and Secret Key will be displayed.

Access the .env and define the keys.
NOCAPTCHA_SITEKEY=your-site-key
NOCAPTCHA_SECRET=your-secret-key

Step # 6 : Add reCAPTCHA V2 to the Form.

Open the Blade file that contains your form (e.g., resources/views/auth/register.blade.php). Insert the reCAPTCHA field at the desired location in the form.
<div class="mt-4">
    <!-- Render the necessary JavaScript for the reCAPTCHA widget -->
    {!! NoCaptcha::renderJs() !!}
    <!-- Display the reCAPTCHA widget -->
    {!! NoCaptcha::display() !!}
    <!-- Display validation error message for the reCAPTCHA response -->
    <span style="color: red;">
        @if($errors->has('g-recaptcha-response'))
            <!-- Show the first error message related to reCAPTCHA -->
            {{$errors->first('g-recaptcha-response')}}
        @endif
    </span>
</div>

Step # 7 : Validate reCAPTCHA v2.

Open the RegisteredUserController and add validation for the g-recaptcha-response field.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
// Importing the NoCaptcha facade for integrating Google reCAPTCHA v2.
use Anhskohbo\NoCaptcha\Facades\NoCaptcha;
class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     */
    public function create(): View
    {
        return view('auth.register');
    }
    /**
     * Handle an incoming registration request.
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
            // Validate the reCAPTCHA response to ensure it is present and valid
            'g-recaptcha-response' => 'required|captcha',
        ]);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        event(new Registered($user));
        Auth::login($user);
        return redirect(route('dashboard', absolute: false));
    }
}

Step # 8 : It's time to test.

Let's run the project and access Register page.
Command : php artisan serve

Let's test the validation. Fill out the registration form without checking the "I'm not a robot" field to verify that the validation is working.

Now, try submitting the form after checking the "I'm not a robot" field.

Finally, you will be redirected to the dashboard.

For more details please refer to the 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