Laravel 9 - Google reCAPTCHA v2

Touseef Afridi
29 Aug 24

Laravel 9 - Google reCAPTCHA v2

In this tutorial, we will discuss how to implement Google reCAPTCHA v2 in Laravel 9. Google reCAPTCHA v2 is a security service that helps distinguish between humans and bots by presenting challenges such as "I'm not a robot" checkboxes or image verification tasks. It protects websites from spam and abuse while minimizing user friction.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

In this guide, we demonstrate how to integrate Google reCAPTCHA v2 into a Laravel 9 application to secure your registration forms. We begin by creating a fresh Laravel project and navigating to its root directory. Next, we set up authentication using Laravel UI, configure the database, and install the biscolab/laravel-recaptcha package. We then obtain the Site Key and Secret Key from Google and add them to the .env file, with an optional step to publish the configuration file for further customization. After including the reCAPTCHA script and widget in the registration form, we update the validation rules to ensure proper verification. Finally, we test the implementation by clearing caches, performing a hard reload, and confirming that the registration form only submits when reCAPTCHA verification succeeds. By following these steps, you’ll have a fully functional reCAPTCHA v2 setup, protecting your Laravel application from automated submissions and bots.

Step # 1 : Setting Up a Fresh Laravel 9 Application.

Let’s start by creating a new Laravel 9 project. If you have the Laravel installer set up globally, simply run.
laravel new recaptchav2
If not, you can use Composer instead.
composer create-project laravel/laravel --prefer-dist recaptchav2
This will create a clean Laravel installation with the default structure and configurations. Working with a fresh project ensures a smooth setup and prevents any conflicts from older code or configurations, giving you a solid base for integrating reCAPTCHA v2.

Step # 2 : Navigate to Your Project.

After creating the Laravel project, the next step is to move into your project’s root directory using the terminal or command prompt.
cd c:xampp/htdocs/recaptchav2
Make sure to replace the path with the correct location where your Laravel project was created. From here, you’ll be ready to run commands and continue with the setup.

Step # 3 : Install Laravel UI Authentication.

Now, let’s set up the authentication scaffolding for Laravel 9. We’ll use the Laravel UI package, which provides basic login and registration views along with the necessary frontend setup. Run the following commands one by one.
composer require laravel/ui
php artisan ui vue --auth
npm install && npm run dev
These commands will install the UI package, generate the authentication views with Vue, pull in the required NPM dependencies, and finally compile the assets with Laravel Mix.

Step # 4 : Set Up the Database.

Next, create a new database named recaptchav2 in your MySQL (or preferred database). After that, update the .env file in your Laravel project with the correct database credentials.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=recaptchav2
DB_USERNAME="your database username"
DB_PASSWORD="your database password"
This configuration will allow your Laravel application to connect to the newly created database.

Step # 5 : Install the Laravel reCAPTCHA v2 Package.

To integrate Google reCAPTCHA v2 into your Laravel 9 project, install the official package by running.
composer require biscolab/laravel-recaptcha
This package makes it easy to add and validate reCAPTCHA in your forms without writing everything from scratch.

Step # 6 : Get Your Google reCAPTCHA v2 Keys.

To use Google reCAPTCHA v2, you’ll need a Site Key and a Secret Key. Follow these steps.
  1. Go to the Google reCAPTCHA Admin Console (https://www.google.com/recaptcha/admin/create) and sign in with your Google account.
  2. Enter a label for your site (this is just for your reference).
  3. Choose reCAPTCHA v2 and select the type of validation you prefer.
  4. Add your domain. For local development, use 127.0.0.1 (Google does not accept localhost). You don’t need to include http:// or https://, and the port is also unnecessary.
  5. Submit the form, and Google will provide you with your Site Key and Secret Key.

Keep these keys handy, we’ll use them in the next step to configure reCAPTCHA in Laravel.

Step # 7 : Add reCAPTCHA Keys to the .env File.

Now, add the Site Key and Secret Key you received from Google into your project’s .env file.
RECAPTCHAV2_SITEKEY="your_site_key_here"
RECAPTCHAV2_SECRET="your_secret_key_here"
These environment variables will be used by the reCAPTCHA package to validate user interactions in your forms.

Step # 8 : Publish the Config File (Optional).

If you’d like to customize the reCAPTCHA settings, you can publish the package configuration file with the following command.
php artisan vendor:publish --provider="Biscolab\ReCaptcha\ReCaptchaServiceProvider"
This will create a config/recaptcha.php file in your project. Open the file and make sure the version is set to v2.
'version' => 'v2', // supported: "v3" | "v2" | "invisible"
Publishing the config isn’t strictly required, but it gives you flexibility if you need to adjust package options later.

Step # 9 : Load the reCAPTCHA v2 Script.

To initialize Google reCAPTCHA, add the package’s JavaScript helper to your master layout file (in the <head> or before the closing </body> tag).
{!! ReCaptcha::htmlScriptTagJsApi() !!}
This will automatically include the required reCAPTCHA script from Google.

Step # 10 : Add reCAPTCHA to the Register Form.

Next, include the reCAPTCHA widget inside your registration form. Place the following snippet just below the password confirmation field.
<div class="form-group row">
    <div class="col-md-6 offset-md-4 mb-2">
        {!! htmlFormSnippet() !!}
    </div>
</div>
This will render the reCAPTCHA box on the registration page, ensuring that users must complete the verification before submitting the form.

Step # 11 : Validate reCAPTCHA v2 on Registration.

To ensure reCAPTCHA is properly verified when users register, update the validation rules in your RegisterController. Add the g-recaptcha-response field with the recaptcha rule.
'g-recaptcha-response' => 'recaptcha',
This tells Laravel to validate the reCAPTCHA response using the package’s built-in rule, blocking any form submission that doesn’t pass Google’s verification.

Step # 12 : Test Your reCAPTCHA v2 Implementation.

Now it’s time to make sure reCAPTCHA is working correctly on your registration form. Before testing, clear any cached configurations to avoid issues.
php artisan optimize:clear
Or alternatively.
php artisan config:cache
php artisan cache:clear
After clearing the cache, refresh your browser to ensure all changes take effect. For a proper update, perform a hard reload using Ctrl + F5 or Ctrl + Shift + R on Windows/Linux, or Cmd + Shift + R on Mac. Once the page reloads, open the registration form you should see the reCAPTCHA widget displayed, and the form will only submit successfully when the verification is completed correctly.

Conclusion

By following this step-by-step guide, you’ve successfully integrated Google reCAPTCHA v2 into your Laravel 9 application. From setting up a fresh project and authentication scaffolding to configuring the database, adding the reCAPTCHA keys, and updating your registration form, you now have a secure system that protects your forms from automated submissions and bots. This setup provides a solid foundation to further enhance your application’s security and user validation processes. For more advanced configurations and options, you can refer to the biscolab/laravel-recaptcha package documentation.

Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering