sushantaryal/laravel-recaptcha

A Laravel package to validate google recaptcha v3

1.0.0 2025-06-16 04:05 UTC

This package is auto-updated.

Last update: 2025-06-16 04:07:44 UTC


README

A Laravel package for validating Google Recaptcha v3.

Installation

You can install the package via Composer:

composer require sushantaryal/laravel-recaptcha

Getting reCAPTCHA keys

Follow the official documentation to get the reCAPTCHA site key and secret key.

Configuration

Add these to your .env:

RECAPTCHA_KEY=
RECAPTCHA_SECRET=
RECAPTCHA_THRESHOLD=0.5

Usage

Form

Follow the official documentation to get the reCAPTCHA HTML code.

Automatically bind the challenge to a button

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

Add a callback function to handle the token.

<script>
    function onSubmit(token) {
        document.getElementById("demo-form").submit();
    }
</script>

Add attributes to your html button.

<button
    class="g-recaptcha"
    data-sitekey="{{ config('recaptcha.key') }}"
    data-callback="onSubmit"
    data-action="submit"
>
    Submit
</button>

OR

Programmatically invoke the challenge

Load the JavaScript API with your sitekey.

<script src="https://www.google.com/recaptcha/api.js?render={{ config('recaptcha.key') }}"></script>

Use the g-recaptcha-response input in your form.

<form action="" method="post" id="recaptcha-form">
    @csrf
    <!-- Add for form inputs -->
    <input type="hidden" name="g-recaptcha-response" value="" />
    <button type="submit">Submit</button>
</form>

Call grecaptcha.execute on each action you wish to protect.

<script>
    const form = document.getElementById('recaptcha-form')
    form.addEventListener('submit', function (event) {
        e.preventDefault();
        grecaptcha.ready(function () {
            grecaptcha.execute('{{ config('recaptcha.key') }}', { action:'submit' }).then(function (token) {
                form.querySelector('input[name="g-recaptcha-response"]').value = token;
                form.submit();
            });
        });
    }
</script>

Backend

You can use the Recaptcha rule in your validation rules:

use Sushant\LaravelRecaptcha\Rules\Recaptcha;

$request->validate([
    'g-recaptcha-response' => ['required', new Recaptcha()],
]);

License

MIT license.