Adding Google reCAPTCHA in Laravel 8/9 to Limit Spam Traffic
In this tutorial, we will show you how to add Google reCAPTCHA to a Laravel application in order to protect your site from too many bot or spam traffic.
reCAPTCHA is a free service from Google. It is used to protect websites from spam and abuse.
Follow the steps below to complete this tutorial:
- Go to Google reCAPTCHA to register your site at https://www.google.com/recaptcha/admin.
- Enter your domain name in the Label field.
- Choose reCAPTCHA v2 for reCAPTCHA type.
- Select "I'm not a robot" Checkbox under reCAPTCHA v2.
- Add localhost and your domain under Domain.
- Choose Accept the reCAPTCHA Terms of Service and Send alerts to owners.
- Choose Submit.
- Copy the SITE KEY and the SECRET KEY to the .env file of your project. Here is an example of .env file where CAPTCHA_SITE_KEY is the SITE KEY and CAPTCHA_SITE_SECRET is the SITE SECRET KEY:
- Create a method in controller to verify user reCAPTCHA input as shown in the example below:
- In routes/web.php, route the /verify-user endpoint to the controller method verifyCaptcha as shown below:
- Run the application and refresh any page more than 10 times. You should be redirected to verify_captcha view.
Here is an example video for registering your site at Google reCAPTCHA:
After your site has been registered at Google reCAPTCHA, you will be taken to a page where you will see SITE KEY and SECRET KEY.
APP_NAME=Laravel APP_ENV=local .................... BROADCAST_DRIVER=log CACHE_DRIVER=file FILESYSTEM_DRIVER=local QUEUE_CONNECTION=sync SESSION_DRIVER=file SESSION_LIFETIME=120 CAPTCHA_SITE_KEY = 6Lc0crEeAAAAADs7q6_I3isdDSA2uHdEO2rncf81 CAPTCHA_SITE_SECRET = 6Lc0crEeAAAAABUHbjPdofTY8gJcMonXdXiMfGGi
If you open this page on a browser, the output will be something like the following:
Go to your app/Providers/RouteServiceProvider.php class and update the configureRateLimiting method as shown in the example below:
The RouteServiceProvider.php file uses the following:
use Illuminate\Cache\RateLimiting\Limit; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Cache; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Route;