Dennis Smink

Laravel Google ReCaptcha ?

Jun 4, 2020 · 1 minute read

When it comes to blocking bots to your website posting malicious content, ReCaptcha from Google is an awesome solution.

In this tutorial i’ll cover how to easily integrate Google ReCaptcha validation in your Laravel Application.

Let’s start by getting our Google key & secret which are required to make ReCaptcha authorize with the Google servers.

Click here to visit the Captcha console.

Add a new site to this console and add the respectively domains under each other. Also add a e-mail adres and press Create.

You will now be presented with your key and secret, add these variables to your .env.example and .env:

GOOGLE_RECAPTCHA_KEY=XXXX
GOOGLE_RECAPTCHA_SECRET=XXXX

Now create this file in your Laravel application: app/Validators/ReCaptcha.php with these contents:

<?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' => env('GOOGLE_RECAPTCHA_SECRET'),
                        'response' => $value
                    ]
            ]
        );

        $body = json_decode((string)$response->getBody());
        return $body->success;
    }
}

Now open your AppServiceProvider.php and add this method in the boot() method:

use Illuminate\Support\Facades\Validator;

public function boot()
{
    Validator::extend('recaptcha', 'App\\Validators\\ReCaptcha@validate');
}

This tells our Laravel core to add a new validation rule method.

Now update your view with this (like a contact form or any form you want to execute this)

@if(env('GOOGLE_RECAPTCHA_KEY'))
     <div class="g-recaptcha"
          data-sitekey="{{env('GOOGLE_RECAPTCHA_KEY')}}">
     </div>
@endif

Also add the JS file to your layout:

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

And thats it! Now how do you use it in a Request validation class? Easy:

$arr = [
    'g-recaptcha-response' => 'required|recaptcha'
];

Do not forget to add the key in your language files to display a better error message when a user does not validate the recaptcha?