In the past, I have published an article on adding Google reCAPTCHA to the Laravel forms. I have shown how to integrate reCAPTCHA v2 in that article. One of our readers asked about adding Google reCAPTCHA v3 in a Laravel application.
The reCAPTCHA v3 has a slightly different behavior. Unlike the older version of reCAPTCHA, you don’t require to put a captcha inside your form. In this version, your visitors don’t need to solve a puzzle. Instead, you will see the reCAPTCHA icon in the bottom-right corner of your website. This v3 version of reCAPTCHA fights against the bots in the background.
In this article, we study how to add reCAPTCHA v3 on the Laravel website. We also study how to stop form submission if reCAPTCHA verification fails.
Get Site Key and Secret Key of reCAPTCHA
For getting started, you first need to register your site with the Google reCAPTCHA service. Go to the Google reCAPTCHA website and click on the ‘+’ icon. On the next page, add the domain of your website, and choose the ‘reCAPTCHA v3’ option. To test the flow on a local server, add ‘localhost’ to the domain field.
Once you hit the submit button, you will get the site key and secret key. Copy these keys. It will require the next steps.
Install and Configure Laravel reCAPTCHA library
Head over to your Laravel project and install the biscolab’s library. This package is built for integrating Google reCAPTCHA in Laravel. It interacts with the reCAPTCHA service and returns either true or false based on the user’s interaction. You should proceed with the form depending on this boolean response.
Open the terminal in your project root directory and run the command:
composer require biscolab/laravel-recaptcha
Upon installation of the library, publish the configuration file using the command below.
php artisan vendor:publish --provider="Biscolab\ReCaptcha\ReCaptchaServiceProvider"
This command creates recaptcha.php
inside the config
directory. Open this file and set the v3
value for the version
key.
return [
...
'version' => 'v3',
...
];
After this, add your site and secret keys of reCAPTCHA to your .env
file as shown below.
RECAPTCHA_SITE_KEY=
RECAPTCHA_SECRET_KEY=
Add Google reCAPTCHA v3 to your Laravel Website
We are done with the configuration and set to add reCAPTCHA on the website. The package we are using comes with a default route protected by Laravel web
middleware. To make this route work, you must embed the csrf-token
HTML meta tag as follows.
<meta name="csrf-token" content="{{ csrf_token() }}">
Next, insert the htmlScriptTagJsApi()
helper before closing the head
tag.
<!DOCTYPE html>
<html>
<head>
...
...
{!! htmlScriptTagJsApi() !!}
</head>
Now go to your website, reload it and you should see the reCAPTCHA icon in the bottom-right corner of the page.
It means you have successfully added Google reCAPTCHA to your website. But it’s not done yet. You have to prevent form submissions if reCAPTCHA validation fails.
Verify Google reCAPTCHA Response
Let’s modify the code by passing an associative array along with configuration parameters to the htmlScriptTagJsApi()
method. It will handle JavaScript validation and allow form submission only if Google reCAPTCHA returns a true
response and the score is above 0.5
. A score greater than 0.5 is considered a legitimate action. Read more about interpreting scores on official documentation.
<head>
...
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type="text/javascript">
function callbackThen(response) {
// read Promise object
response.json().then(function(data) {
console.log(data);
if(data.success && data.score > 0.5) {
console.log('valid recpatcha');
} else {
document.getElementById('registerForm').addEventListener('submit', function(event) {
event.preventDefault();
alert('recpatcha error');
});
}
});
}
function callbackCatch(error){
console.error('Error:', error)
}
</script>
{!! htmlScriptTagJsApi([
'callback_then' => 'callbackThen',
'callback_catch' => 'callbackCatch',
]) !!}
</head>
Reload the page and check in the browser console, you will see the response of the Google reCAPTCHA. In my case, it’s shown as a screenshot below.
Google reCAPTCHA returns a true
value for success
key and a score is 0.9
. That means your form is safe to proceed.
Now to test if the code is preventing form submission for a false value, make your secret key invalid. You can remove the last 2 characters from your secret key.
Reload the page and you should receive a false
value for the success
key. In JavaScript, I have prevented the form execution if you don’t get a true value. Note I used the form id registerForm
to stop the execution. Adjust this value with your form id. Now you won’t be able to submit a form as your reCAPTCHA verification is failing.
It’s all about adding Google reCAPTCHA v3 on the Laravel website. I hope you liked the tutorial and will take benefit from it to avoid spam entries on your application.
Related Articles
- PayPal Payments Pro Integration in Laravel
- How to Create a Blog with Laravel
- How to Create Honeypot for Battling Form Spam in Laravel
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
Can you put the code on github link?
Thanks
how to test google recaptcha v3 working or not.. pls tell us..
Steps for it are mentioned in the last paragraphs of the article.
well how to show that in the page
You need to add {!! htmlScriptTagJsApi() !!} in head tag.
verey very awesome
you are fantastic
thanks for this teaching
Kindly check after following this post spamming is stopped?
I have implemented it successfully and spamming is not stoped so this is not the correct method of implementation.
I ran
composer require biscolab/laravel-recaptcha”
and
composer update
And still havng issues with htmlScriptTagJsApiV3
In article composer command is:
composer require biscolab/laravel-recaptcha:^3.0
You missed ^3.0
Thank you but how can we check and understand that it works correctly?
Hi,
i follow your instructions but i’ve that error :
Call to undefined function htmlScriptTagJsApiV3()
so i can’t open homepage, how can i defined that function?
Thanks
htmlScriptTagJsApiV3() is already defined in biscolab/laravel-recaptcha library? Did you run all commands mentioned in the article?
run “composer require biscolab/laravel-recaptcha” (without version number) or run “composer update”