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!
Step # 1 : Create fresh Laravel project with Breeze Auth.
Two commands to create fresh laravel project.
Global Command : laravel new reCAPTCHAV3
Or use
Non Global Command : composer create-project laravel/laravel --prefer-dist reCAPTCHAV3
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/reCAPTCHAV3
Step # 3 : Install reCAPTCHA V3 package.
Run the following command.
Command : composer require josiasmontag/laravel-recaptchav3
Step # 4 : Publish the Config file (Optional).
Run the following command.
Command : php artisan vendor:publish --provider="Lunaweb\RecaptchaV3\Providers\RecaptchaV3ServiceProvider"
Step # 5 : Obtain reCAPTCHA V3 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.
Select reCAPTCHA v3 as the version.
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.
RECAPTCHAV3_SITEKEY="Define your SITE KEY here"
RECAPTCHAV3_SECRET="Define your SITE SECRET here"
Step # 6 : Initialize reCAPTCHA JavaScript.
Copy the following code and add it to the header or footer of your master layout.
{!! RecaptchaV3::initJs() !!}
Step # 7 : Update the register.blade.php file.
Open the register.blade.php file and add the RecaptchaV3 field alongside the register button.
{!! RecaptchaV3::field('register') !!}
<x-primary-button class="ms-4">
{{ __('Register') }}
</x-primary-button>
Step # 8 : Validate reCAPTCHA v3.
Open the RegisterController and add validation for the g-recaptcha-response field if needed.
'g-recaptcha-response' => 'required|recaptchav3:register,0.5',
Step # 9 : It's time to test.
Let's run the project and access Register page.
Command : php artisan serve
Use the browser's Inspect tool to examine the register button. You will find the hidden input fields associated with the g-recaptcha-response.
To inspect the g-recaptcha-response, modify the store method in the RegisteredUserController as shown below.
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));
}
Now that you’ve inspected the g-recaptcha-response and verified its presence, you’re good to proceed. Remove the dd statement from the RegisteredUserController to allow the registration process to work as intended.
Step # 10 : Example of Validation Logic (Optional)
Use the Lunaweb\RecaptchaV3\Facades\RecaptchaV3 facade to implement conditional logic based on the reCAPTCHA score. Here's an example
<?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));
}
}
And you can build you logic based on score.
For more details please refer to 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