Laravel 11 - How to Integrate Google reCAPTCHA v3
Laravel 11 - How to Integrate Google reCAPTCHA v3
In this tutorial, we’ll see how to integrate Google reCAPTCHA V3 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!
Quick Overview
This guide provides a step-by-step process to integrate Google reCAPTCHA v3 into a Laravel project with Breeze authentication. It covers setting up a fresh Laravel project, installing the necessary reCAPTCHA package, and configuring the Site Key and Secret in the .env file. The guide demonstrates how to initialize reCAPTCHA V3 on the front end, add the reCAPTCHA field to the registration form, and validate the user's response in the backend. It also includes a method for inspecting the reCAPTCHA response and optional logic to handle the score for additional security measures. By following this guide, you can effectively protect your registration process from bots and spam, ensuring a smoother and safer user experience.
Step # 1 : Create a New Laravel Project with Breeze Authentication.
If Laravel is installed globally, use the following command to create a new project.
laravel new reCAPTCHAV3
Or
If Laravel is not installed globally, use Composer instead.
composer create-project laravel/laravel --prefer-dist reCAPTCHAV3
You'll be prompted to configure the setup.
- Would you like to install the starter kit? — Choose "Breeze"
- After selecting Breeze, you'll be asked to choose your stack. — Choose Blade
- After selecting Blade, you'll be asked for dark mode support. — Choose no
- After selecting No, you'll be asked about testing framework.. — Choose Pest
- After selecting Pest, you'll be asked to select the database for your application. — Choose mysql
- After selecting MySql, you'll be asked if you want to run the default database migration. — Type yes
After completing these steps, your Laravel project will be ready.
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/reCAPTCHAV3
Step # 3 : Install the reCAPTCHA V3 Package.
Run the following command to install the package.
composer require josiasmontag/laravel-recaptchav3
This installs the package and updates composer.json with its dependencies.
Step # 4 : Publish the Config file (Optional).
Run the following command.
php artisan vendor:publish --provider="Lunaweb\RecaptchaV3\Providers\RecaptchaV3ServiceProvider"
This publishes the package's configuration file to the config directory.
Step # 5 : Obtain reCAPTCHA V3 Site Key and Secret.
To integrate reCAPTCHA V3, you need to obtain the Site Key and Secret Key from Google's reCAPTCHA Admin Console.
- Visit the 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 (this will help you identify your keys later).
- Select reCAPTCHA v3 as the version.
- Define your site's domain(s) for security purposes.
- Click Submit to generate your Site Key and Secret Key.
Once you submit, you'll be redirected to a page where your Site Key and Secret Key will be displayed.
Next, open your .env file in your Laravel project and define the keys like so.
RECAPTCHAV3_SITEKEY="Define your SITE KEY here"
RECAPTCHAV3_SECRET="Define your SITE SECRET here"
Replace Define your SITE KEY here and Define your SITE SECRET here with the keys you just generated. This step connects your Laravel app with Google's reCAPTCHA service.
Step # 6 : Initialize reCAPTCHA V3 JavaScript.
Copy the following code and add it to the header or footer of your master layout.
{!! RecaptchaV3::initJs() !!}
This will initialize the reCAPTCHA V3 JavaScript on your site, enabling the reCAPTCHA functionality on the front-end for pages that require it.
Step # 7 : Add reCAPTCHA Field to the Registration Form.
Open the register.blade.php file and add the following code to include the RecaptchaV3 field alongside the register button.
{!! RecaptchaV3::field('register') !!}
<x-primary-button class="ms-4">
{{ __('Register') }}
</x-primary-button>
This will initialize the reCAPTCHA V3 validation on the registration form, and the reCAPTCHA score will be validated in the background when the form is submitted.
Step # 8 : Validate reCAPTCHA v3.
Open the RegisterController and add the following validation rule for the g-recaptcha-response field.
'g-recaptcha-response' => 'required|recaptchav3:register,0.5',
This will validate the reCAPTCHA response and ensure that it meets the specified score threshold (in this case, 0.5) before allowing the registration to proceed.
Step # 9 : It's time to test.
Let's run the project and access Register page.
php artisan serve
Then, open the Register page in your browser and use the Inspect tool to check the page. You should find the hidden input fields related to the g-recaptcha-response that are automatically added by reCAPTCHA V3 for validation during form submission.
To inspect the g-recaptcha-response, modify the store method in the RegisteredUserController as follows.
public function store(Request $request): RedirectResponse
{
dd($request->all());
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
'g-recaptcha-response' => 'required|recaptchav3:register,0.5',
]);
$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));
}
After submitting the registration form, the dd($request->all()) will display the request data, including the g-recaptcha-response field. This allows you to inspect whether the reCAPTCHA response is being sent properly before the validation occurs.
Now that you've inspected the g-recaptcha-response and confirmed its presence, you can proceed. Remove the dd() statement from the RegisteredUserController to allow the registration process to function properly.
Step # 10 : Example of Validation Logic (Optional)
You can use the Lunaweb\RecaptchaV3\Facades\RecaptchaV3 facade to implement conditional logic based on the reCAPTCHA score. Here’s an example of how you might set it up in your RegisteredUserController.
<?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;
//Facde
use Lunaweb\RecaptchaV3\Facades\RecaptchaV3;
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
{
// Verify the reCAPTCHA response and retrieve the score for the 'register' action
$score = RecaptchaV3::verify($request->get('g-recaptcha-response'), 'register');
// Check if the score is greater than 0.5 (indicating a likely legitimate user)
if ($score > 0.5) {
// Debug output: Score is acceptable, proceed with the desired action
dd($score, "Do This");
} else {
// Debug output: Score is too low, handle as a potential bot or invalid response
dd($score, 'Do That');
}
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
'g-recaptcha-response' => 'required|recaptchav3:register,0.5',
]);
$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));
}
}
This code allows you to build custom logic based on the reCAPTCHA score. If the score is above 0.5, the registration continues as usual. If the score is too low, you can handle it as a potential bot or invalid submission.
You can customize your logic based on the reCAPTCHA score.
Conclusion
By following this guide, you've successfully integrated Google reCAPTCHA V3 into your Laravel project with Breeze authentication, enhancing your registration form's security against bots and spam. With reCAPTCHA V3 in place, your application is now better protected, and you can easily extend this setup to other forms. This simple integration ensures a secure and smooth user experience for your site.
For more details, check the package documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments