Laravel 9 - Google reCAPTCHA v3
Laravel 9 - Google reCAPTCHA v3
In this tutorial, we will discuss how to implement Google reCAPTCHA v3 in Laravel 9. Google reCAPTCHA v3 is a tool that protects websites from spam and abuse by analyzing user interactions to detect and prevent automated bot activities. It provides a seamless user experience without interrupting users with CAPTCHA challenges.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
In this tutorial, we covered the process of integrating Google reCAPTCHA v3 into a Laravel project to protect the registration form from bots. We began by creating a fresh Laravel project and setting up UI authentication to handle user login and registration. After configuring the database, we installed the Laravel reCAPTCHA v3 package and added the required keys to the .env file. Next, we initialized the reCAPTCHA JavaScript on the pages where it's needed and replaced the default submit button in the registration form with the reCAPTCHA field. Validation was then added to ensure that the reCAPTCHA response is verified before the form is submitted. Finally, we tested the implementation to ensure everything worked as expected and demonstrated how to add custom validation logic based on the reCAPTCHA score for further control.
Step # 1 : Create Fresh Laravel Project.
Create a fresh Laravel project named reCAPTCHA using the global Laravel installer command.
laravel new reCAPTCHA
Or
If the Laravel installer is not globally installed, use Composer to create the project named reCAPTCHA
composer create-project laravel/laravel --prefer-dist reCAPTCHA
Step # 2 : Install UI authentication.
Run the following command to install UI authentication, generate the authentication scaffolding, and compile the necessary frontend assets using Laravel Mix.
composer require laravel/ui
php artisan ui vue --auth
npm install && npm run dev
Step # 3 : Create a Database.
Create a database named recaptcha and update the .env file with the database connection details like database name, username, and password.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=recaptcha
DB_USERNAME="your database username"
DB_PASSWORD="your database password"
Step # 4 : Install Laravel ReCAPTCHA v3 package.
Install the Laravel reCAPTCHA v3 package by running the composer command to handle reCAPTCHA integration in the project.
composer require josiasmontag/laravel-recaptchav3
Step # 5 : Let's get the google ReCAPTCHA v3 site key and secret key.
Access the Google reCAPTCHA admin page (https://www.google.com/recaptcha/admin/create), sign in or create an account, create a label for your site, select the reCAPTCHA version, and define the domain (127.0.0.1). For Google reCAPTCHA v3, you should define 127.0.0.1 as the domain name, localhost is not accepted. HTTP or HTTPS is not required, and there is no need to specify the port. Submit the form, and you will get the site key and secret key.
Step # 6 : Add ReCAPTCHA site key and secret key to env.
Add the Google reCAPTCHA v3 site key and secret key to your .env file. Replace Your site key here and Your secret key here with the actual keys obtained from the Google reCAPTCHA admin page.
RECAPTCHAV3_SITEKEY="Your site key here"
RECAPTCHAV3_SECRET="Your secret key here"
Step # 7 : Publish Config File (Optional)
Optionally, publish the configuration file for the reCAPTCHA v3 package. Below command will create a config file that you can modify as needed.
php artisan vendor:publish --provider="Lunaweb\RecaptchaV3\Providers\RecaptchaV3ServiceProvider"
Step # 8 : Init reCAPTCHA JavaScript.
Add the reCAPTCHA JavaScript initialization code to your master layout. This will load the necessary reCAPTCHA scripts on your pages. Copy and add it to header or footer of master layout.
{!! RecaptchaV3::initJs() !!}
Step # 9 : Access the register.blade.php file.
In the register.blade.php file, replace the default submit button with the reCAPTCHA field. This ensures that the reCAPTCHA verification is triggered when the form is submitted.
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
To
{!! RecaptchaV3::field('register') !!}
<input type="submit" value="Register"></input>
Step # 10 : Validating reCAPTCHA
In the RegisterController, add validation for the g-recaptcha-response to ensure that the reCAPTCHA verification is successful before allowing the form submission. The recaptchav3 rule checks the reCAPTCHA response against the configured site key and secret key.
'g-recaptcha-response' => 'required|recaptchav3:register,0.5'
Step # 11 : It's time to test.
Start the Laravel development server and visit the Register page to test the reCAPTCHA functionality.
php artisan serve
Step # 12 : Validation Logic example (Optional)
In this step, we're implementing custom validation logic for Google reCAPTCHA v3 based on the score. The 'verify' method checks the score for the reCAPTCHA response and you can decide what to do based on that score. For example, if the score is below a threshold, you can reject the submission. The 'dd' function here is used to inspect the score, and you can replace it with your own logic for handling different scores.
Import RecaptchaV3 facade at the top of your controller
use Lunaweb\RecaptchaV3\Facades\RecaptchaV3;
Use condition based on score.
$score = RecaptchaV3::verify($request->get('g-recaptcha-response'), 'register');
if ($score > 0.5) {
dd($score, "Do This");
} else {
dd($score, 'Do That');
}
Conclusion
Following the outlined steps, you’ve successfully integrated Google reCAPTCHA v3 with your Laravel application. This setup not only secures your registration form from bot submissions but also gives you flexibility in handling the validation based on reCAPTCHA scores. With the basic and optional configurations, you’ve ensured that the form is both user-friendly and protected, completing the reCAPTCHA integration seamlessly in your project.
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