Hi there. I want to share with you how I implemented Google’s reCAPTCHA v3 in my Laravel app.

Securing HTML forms from bots is an essential part of the security of any web app these days. One common and easy solution to this is implementing a captcha system. And Google’s reCAPTCHA v3 makes it quite easy to both implement as a developer and use as a user (v3 users do not have to select images to verify).

Let’s get started.

Check out BestOfLaravel.com – One place to learn all things Laravel

Registering a New Site

First off, we need to register our site in Google reCAPTCHA Admin and gain usage keys. When you add your site, also add localhost in the list of domains, this will allow you to use the same key for development.

Google reCAPTCHA admin console

Once you submit these details, you should see two keys generated for your domain. One is the SITE KEY which is used in the front-end and the other is the SECRET KEYfor usage in the server.

Front-End Setup

The front-end setup is pretty simple. Choose the page in which you want to implement reCAPTCHA, in my case I have a contact form on a page.

The below code shows a contact form with a hidden input named recaptcha (it can be any name). Then at the end of that page add the reCAPTCHA’s JS library and once it’s ready we get a token and set it to the recaptcha input.

Front-end setup

Backend Setup

Backend Setup

The above code checks if the current request is from a bot. We do this by sending a post request to Google’s reCAPTCHA API with the SECRET KEY and the TOKEN from the front-end.

The resulting JSON has a property (success) that is set to false when Google detects a request from a bot. Below is an example of what is returned.

JSON from Google Api

Optimizing the Setup

Here’s a list of optimizations you could do to the above setup.

  1. Move the configuration keys to the .env file.
  2. Move the verification logic to a custom validator.

Both of these are covered in the tutorial to which I’ve linked below.


There you have it. It’s pretty simple to add Google’s reCAPTCHA to your app. I would suggest you add this to all pages that can be visited by a bot. If you have any doubts, leave your questions below and I will try to help you.

Related Tutorials

Source link

Write A Comment