Introduction

We’ve all seen reCAPTCHA at one point or another – that previously hateful box on every contact form or registration page that you’d take half a dozen stabs at before finally getting it right. Thankfully it’s been replaced lately with a much more intelligent implementation that doesn’t usually require much more than for someone to check a box.

With the original version being deprecated entirely these days and the amount of Laravel development we carry out, we’ve been using a simple in-house module to implement reCAPTCHA quickly and easily.

How does it work?

The most straightforward method involves simply installing and configuring the module, adding a line to a form validator and choosing where to display the widget within the form. With the latest versions of Laravel this can all be accomplished in a matter of minutes.

Installing & Configuring

To get started, install the module with composer

composer require scaffold-digital/laravel-recaptcha

Next, you’ll want to generate a site key and secret key at https://www.google.com/recaptcha/admin and then copy those values into a new file in your ‘config’ directory: “config/recaptcha.php”

<?php
return [
    'key' => 'YOUR SITE KEY',
    'secret' => 'YOUR SECRET KEY',
];

That’s it! You’ve configured everything and it’s ready to be used.

Displaying the reCAPTCHA widget

There’s two parts to this. First off, you’ll need to include some Javascript just before your closing <head> tag. We’ve got a function for this, just follow the example below:

<head>
...
{!! Recaptcha::getScript(); !!}
</head>

Next, choose the point in your form that you want to display the widget itself. This can go anywhere really but usually ends up near the bottom like so:

<body>
...
<form method="POST">
<div class="form-group">{!! Recaptcha::getWidget(); !!}</div>
</form>
...
</body>

And lastly, validating the response

You’re basically done. The last part of the process is to make sure the reCAPTCHA response is validated as part of the form submission. If you’ve already got a validator for this, you just need to add a single line to it. Use the example below as a guide:

<?php
namespace App\Controllers\MyController;

class MyController extends Controller {

    public function postForm(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'g-recaptcha-response' => 'recaptcha'
        ]);
    }

}

You’re ready go to!

Laravel will now enforce reCAPTCHA validation along with any other form fields. What’s more, if you’re displaying validation errors on the page already then this method will include an error if reCAPTCHA validation fails without you needing to do anything else.

More Info

There is other functionality in this module not covered here, this is just the most basic implementation. If you’d like any more info, feel free to check it out on Github. We’d also appreciate any contributions or suggestions you have.