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:

  1. Go to Google reCAPTCHA to register your site at https://www.google.com/recaptcha/admin.
  2. Enter your domain name in the Label field.
  3. Choose reCAPTCHA v2 for reCAPTCHA type.
  4. Select "I'm not a robot" Checkbox under reCAPTCHA v2.
  5. Add localhost and your domain under Domain.
  6. Choose Accept the reCAPTCHA Terms of Service and Send alerts to owners.
  7. Choose Submit.
  8. 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.

  9. 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:
  10. 
    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
    
  11. The next step is to include the important JavaScript resource and a g-recaptcha tag for rendering the reCAPTCHA widget on your web page. Create a verify_captcha.php view and make the code look something like below:
  12. Implementing Google reCAPTCHA in laravel frontend

    If you open this page on a browser, the output will be something like the following:

    Google reCAPTCHA in laravel website
  13. Create a method in controller to verify user reCAPTCHA input as shown in the example below:
  14. Google reCAPTCHA laravel backend

    Go to your app/Providers/RouteServiceProvider.php class and update the configureRateLimiting method as shown in the example below:

    rate limiting in laravel 8/9

    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;    
    
  15. In routes/web.php, route the /verify-user endpoint to the controller method verifyCaptcha as shown below:
  16. rate limiting in laravel 8
  17. Run the application and refresh any page more than 10 times. You should be redirected to verify_captcha view.