Adding Google reCAPTCHA v2 Checkbox to your Laravel Application

Google reCAPTCHA Google reCAPTCHA Checked

What is reCAPTCHA?

reCAPTCHA is a free service that protects your site from spam and abuse. It uses advanced risk analysis techniques to tell humans and bots apart.

[img na contact stranici]

You will need Google Account where you will create Google reCAPTCHA v3 for your domain.

you can test with localhost

Add to your .env

GOOGLE_RECAPTCHA_KEY=6LczpNMZAAAAAJQZR7yiHV1E263cHWmVaQf0I4ya
GOOGLE_RECAPTCHA_SECRET=6LczpNMZAAAAACUJQwFdiJ7zG1Cfat2UC-CUH2yz

Add to your form

<div>
    <div id="googleRecaptcha"></div>

    {!! ($errors->has('g-recaptcha-response') ? '<p>'.$errors->first('g-recaptcha-response').'</p>' : '') !!}
</div>

Include js file just before closing </head>

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallbackRecaptcha&render=explicit"
    async defer>
</script>
<script type="text/javascript">
    var onloadCallbackRecaptcha = function() {
        grecaptcha.render('googleRecaptcha', {
            'sitekey' : '{ {env('GOOGLE_RECAPTCHA_KEY')}}'
        });
    };
</script>

Create Custom Validation Rule

Create Custom Validation Rule

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Client;

class GoogleRecaptcha implements Rule
{
    public function passes($attribute, $value)
    {
        $client = new Client();
        $response = $client->post('https://www.google.com/recaptcha/api/siteverify',
            [
                'form_params' => [
                    'secret' => env('GOOGLE_RECAPTCHA_SECRET', false),
                    'remoteip' => request()->getClientIp(),
                    'response' => $value
                ]
            ]
        );
        $body = json_decode((string)$response->getBody());
        return $body->success;
    }

    public function message()
    {
        return 'Are you a robot?';
    }
}

Validate

$validator = \Validator::make(
    $request->except('_token'),
    [
        'g-recaptcha-response' => [
            'required', new \App\Rules\GoogleRecaptcha
        ]
        'name' => 'required', // example
        'email' => 'required|email', // example
        'text' => 'required', // example

    ]
);

if ($validator->fails()) {
    return redirect()->back()->withErrors($validator)->withInput();
}
;