Laravel 11 - How to Integrate Google reCAPTCHA v2
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!
Quick Overview
This guide walks you through integrating Google reCAPTCHA V2 into a Laravel project with Breeze authentication. It covers the process of setting up a fresh Laravel project, installing the necessary reCAPTCHA package, obtaining your Site Key and Secret from Google, and configuring them in your Laravel application. The guide also shows how to add the reCAPTCHA widget to your registration form and validate the user's response. Finally, it explains how to test the reCAPTCHA integration to ensure it's working properly. This setup helps protect your application from spam and bot submissions, providing an extra layer of security for your site.
Step # 1 : Create fresh Laravel project with Breeze Authentication.
If you have Laravel installed globally, use the following command.
laravel new reCAPTCHAV2
Or
If you don’t have Laravel installed globally, use the Composer command.
composer create-project laravel/laravel --prefer-dist reCAPTCHAV2
After running one of these commands, you’ll be prompted with the following options.
- Would you like to install the starter kit? — Select Breeze.
- Choose your stack. — Select Blade.
- Dark mode support. — Select no.
- Testing framework. — Select Pest.
- Database for your application. — Select mysql.
- Run the default database migration? — Select yes.
This process will set up a fresh Laravel project with Breeze authentication, Pest for testing, MySQL as the database, and will run the default migration to create the necessary tables for authentication and other default features.
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder by running the following command.
cd c:xampp/htdocs/reCAPTCHAV2
This will bring you to the root directory of your newly created Laravel project, where you can begin further setup and configurations.
Step # 3 : Install reCAPTCHA V2 package.
Run the following command to install the reCAPTCHA V2 package.
composer require anhskohbo/no-captcha
This will download and install the necessary package to integrate Google reCAPTCHA V2 into your Laravel application.
Step # 4 : Publish the Config file (Optional).
Run the following command to publish the configuration file for reCAPTCHA.
php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"
This will generate a configuration file for the reCAPTCHA settings in your Laravel application, which you can customize as needed.
Step # 5 : Obtain reCAPTCHA V2 Site Key and Site Secret.
To integrate reCAPTCHA V2, 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).
- Choose reCAPTCHA v2 and select the I'm not a robot checkbox option.
- Define your site's domain(s) for security purposes.
- Click Submit to generate your reCAPTCHA keys.
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.
NOCAPTCHA_SITEKEY=your-site-key
NOCAPTCHA_SECRET=your-secret-key
Replace your-site-key and your-secret-key with the keys you just generated. This step connects your Laravel app with Google's reCAPTCHA service.
Step # 6 : Add reCAPTCHA v2 to the Form.
Open the Blade file that contains your form (e.g., resources/views/auth/register.blade.php) and insert the reCAPTCHA field at the desired location in the form. Add the following code.
<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>
This will render the reCAPTCHA widget and display any validation error message related to the response.
Step # 7 : Validate reCAPTCHA v2.
Open the RegisteredUserController and add validation for the g-recaptcha-response field in the store method. This ensures that the reCAPTCHA response is present and valid when the user registers. Update your controller as follows.
<?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));
}
}
In this step, we added the validation rule 'g-recaptcha-response' => 'required|captcha' to ensure that the reCAPTCHA response is submitted and valid. If the response is invalid or missing, the validation will fail, and an error will be returned to the user.
Step # 8 : It's time to test.
Now that everything is set up, let's run the project and access the Register page to test the reCAPTCHA integration.
php artisan serve
Once the server is running, navigate to the registration page by visiting the URL provided by the development server (typically http://127.0.0.1:8000/auth/register).
To verify the reCAPTCHA validation, try submitting the registration form without checking the I'm not a robot checkbox. You should see an error message indicating that the reCAPTCHA validation failed.
Next, check the I'm not a robot checkbox and submit the form again. This time, the form should pass the validation, and you'll be redirected to the dashboard.
This test ensures that the reCAPTCHA is properly integrated and validated during registration. Once confirmed, you can proceed with any additional customization or adjustments.
Conclusion
By following this guide, you've successfully integrated Google reCAPTCHA V2 into your Laravel project with Breeze authentication. This implementation ensures that your registration form is protected from bots and spam, enhancing the security of your application. With the reCAPTCHA widget added and validated, your Laravel project is now equipped with an effective mechanism for preventing automated submissions. You can easily extend this integration to other forms in your application as needed. This simple yet powerful tool significantly improves user experience while maintaining a secure environment.
For more details, be sure to 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