Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Adding Google reCAPTCHA v3 to Your Laravel App

DZone 's Guide to

Adding Google reCAPTCHA v3 to Your Laravel App

reCAPTCHA is a great way to weed out bots from your site/app. Learn how to easily integrate it into your code using the reCAPTCHA API.

· Web Dev Zone ·
Free Resource

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 LaravelCollections.com - a growing collection of great Laravel resources

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.

Conclusion

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

Topics:
web dev ,php tutorial ,laravel tutorial ,recaptcha ,api integration

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}