How to Add I’m not a robot captcha in Laravel Forms

Are you looking to add Google reCAPTCHA in your Laravel forms? Google reCAPTCHA helps to protect the forms against bots that result to save us from spams. If you are not protecting your forms then probably you are getting a ton of spams into the database.

At the time of writing, Google provides 2 versions of reCAPTCHA – v2 and v3. The reCAPTCHA v3 places an icon to the bottom-right corner of your pages and they verify requests with a score. On the other hand, reCAPTCHA v2 verifies requests with a challenge. In this article, we study reCAPTCHA v2 and we gonna validate requests with the “I’m not a robot” checkbox.

Why need of Google reCAPTCHA?

An Internet bot is a system that runs automated scripts on the Internet. They target the website forms to send spams into the database. Basically, this system works at a much higher rate than humans alone. We always want a real human to interact with our website forms, not a bot.

By adding Google reCAPTCHA, we can protect our website forms against these Internet bots, their spams, and abuse. It is impossible for an automated system to resolve the challenge set by reCAPTCHA. And your form will not be submitted until the challenge is resolved. A human can easily resolve these challenges and submit a form.

Setup Google reCAPTCHA on Your Laravel Website

To get started, you need to first register the site on Google. Choose the option reCAPTCHA v2 and “I’m not a robot” Checkbox as shown in screenshot below.

reCAPTCHA

Upon registering the site, copy the site key and secret key which we will need in a moment.

We have to add reCAPTCHA in the Laravel project. For accomplishing the task, I am going to use the anhskohbo/no-captcha library.

Open the command prompt in the root directory of your project and run the command:

composer require anhskohbo/no-captcha

Open ‘config/app.php’ file and add the below line to the ‘providers’ array.

Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,

Add class alias to the aliases array:

'NoCaptcha' => Anhskohbo\NoCaptcha\Facades\NoCaptcha::class,

Publish the config file using the command:

php artisan vendor:publish --provider="Anhskohbo\NoCaptcha\NoCaptchaServiceProvider"

Next, open the .env file and specify the reCAPTCHA keys as follows.

NOCAPTCHA_SECRET=secret-key
NOCAPTCHA_SITEKEY=site-key

Make sure to replace placeholders secret-key, site-key with the actual values.

Clear the configuration cache by running the below command.

php artisan config:clear 

Adding Google reCAPTCHA to the Form in Laravel

At this stage, you are completed with the basic setup required for reCAPTCHA. Now let’s write some code and make it in action.

Open your view file where you want to add I’m not a robot checkbox. On the top of blade file initialize the JS source as follows:

{!! NoCaptcha::renderJs() !!}

Add the below single line statement at the place where you want to display the reCAPTCHA checkbox. The best place is before the submit button.

{!! NoCaptcha::display() !!}

As an example, let’s create a form with few fields and add reCAPTCHA to it using the code below.

{!! NoCaptcha::renderJs() !!}

@if ($errors->has('g-recaptcha-response'))
    <span class="help-block">
        <strong>{{ $errors->first('g-recaptcha-response') }}</strong>
    </span>
@endif
<form action="{{ url('ROUTE_HERE') }}" method="post">
    <p>Name: <input type="text" name="fullname" /></p>
    <p>Email: <input type="email" name="email" /></p>
    <p>Message: <textarea name="message"></textarea></p>
    {!! NoCaptcha::display() !!}
    {{ csrf_field() }}
    <p><input type="submit" name="submit" value="Submit" /></p>
</form>

After adding the above lines, you will see reCAPTCHA appear something like shown in the below screenshot.

I'm not a robot captcha

In the above code, I also added a code that displays an error if it occurs on validating a reCAPTCHA.

Now, we have to validate the reCAPTCHA on form submission. To achieve this, I will use Laravel Validator as follows.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ContactController extends Controller
{
    ...
    ...
    public function store(Request $request)
    {
        $messages = [
            'g-recaptcha-response.required' => 'You must check the reCAPTCHA.',
            'g-recaptcha-response.captcha' => 'Captcha error! try again later or contact site admin.',
        ];

        $validator = Validator::make($request->all(), [
            'g-recaptcha-response' => 'required|captcha'
        ], $messages);

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

        // process the form
    }   
}

Here, I have included the facade ‘Validator’ and validating a reCAPTCHA in the ‘store’ method. If it fails to validate then it will throw an error.

That’s it! You have successfully added reCAPTCHA v2 with I’m not a robot checkbox to the Laravel form. Now, your form will not be submitted until the visitor resolves the reCAPTCHA challenge.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

4 thoughts on “How to Add I’m not a robot captcha in Laravel Forms

  1. Hi, I am Serena and I enjoyed your article a great deal. You truly worked admirably. The article is Very Interesting and Informative simultaneously, a debt of gratitude is in order for offering this to us.

Leave a Reply

Your email address will not be published. Required fields are marked *