How to add Google ReCaptcha to your Laravel project

How to add Google ReCaptcha to your Laravel 9 project

Posted by Luke Beeno on November 8, 2022

How to add Google ReCaptcha to your Laravel project

How to add Google ReCaptcha to your Laravel 9 project

Posted by Luke Beeno on November 8, 2022

Google ReCaptcha is a tool that is used to check if a user is human and therefore prevent bots from engaging with your website in places you don't want.

Here is how you can set up Google ReCaptcha on your in your project:

Step 1, You will need to get a site key and sercret key from Google Recaptcha

Step 2. Add keys to .env file

GOOGLE_RECAPTCHA_KEY=ABCDE6abcdef
GOOGLE_RECAPTCHA_SECRET=ABCDE6abcdef

If your testing locally use these keys:

GOOGLE_RECAPTCHA_KEY=6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
GOOGLE_RECAPTCHA_SECRET=6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

Step 3. Add reference to key in service file

Go to /config/services.php and add snippet below:

'recaptcha' => [
   'key' => env('GOOGLE_RECAPTCHA_KEY'),
   'secret' => env('GOOGLE_RECAPTCHA_SECRET'),
],

Step 4. Create custom validator

Go to app folder and create Validator directory 

Create a file called ReCaptcha.php within Valiator folder and place code snippet below

<?php
namespace App\Validators;
use GuzzleHttp\Client;
class ReCaptcha
{
    public function validate($attribute, $value, $parameters, $validator)
    {
        $client = new Client;
        $response = $client->post(
            'https://www.google.com/recaptcha/api/siteverify',
            [
                'form_params' =>
                    [
                        'secret' => config('services.recaptcha.secret'),
                        'response' => $value
                    ]
            ]
        );
        $body = json_decode((string)$response->getBody());
        return $body->success;
    }
}

Step 5. Register custom validator

Go to app/Providers/AppServiceProvider.php and add below snippet to boot method

Validator::extend('recaptcha', 'App\\Validators\\ReCaptcha@validate');

Step 6. Add validator to your form as below

@if(config('services.recaptcha.key'))
   <div class="g-recaptcha"
     data-sitekey="{{config('services.recaptcha.key')}}">
   </div>
   @error('g-recaptcha-response')
      <div class="error-txt">{{ $message }}</div>
   @enderror
@endif

Step 7. Add validation of reCaptcha to form validation request 

Put this snippet in request rules

'g-recaptcha-response' => 'required|recaptcha'

It will look like below:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{

  return [
      'firstname'             => 'required|max:255|string',
      'lastname'              => 'max:255|string',
      'email'                 => 'required|max:255|email',
      'g-recaptcha-response' => 'required|recaptcha'
  ];
}

Step 8. Finally, add Google js script to header 

<script src='https://www.google.com/recaptcha/api.js'></script>