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

Are you looking to add Google reCAPTCHA to your Laravel forms? Google reCAPTCHA helps to protect the forms against bots and eventually from spam. If you are not using reCAPTCHA on your forms then probably you are getting a ton of spam emails. And if you are storing form details then your database is filled with tons of garbage.

One must use reCAPTCHA on the website. It saves your precious time and money by clearing spam.

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

Why need Google reCAPTCHA?

An Internet bot is a system that runs automated scripts on the Internet. They target the website forms to send spam. 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 v2, we can protect our website forms against these Internet bots, their spam, 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 your website on Google. Choose the option reCAPTCHA v2 and the “I’m not a robot” Checkbox as shown in the screenshot below.

google-recaptcha

Upon registration, copy the site key and secret key which will be required in a moment.

We have to add reCAPTCHA to the Laravel project. For accomplishing this task, I am going to use the anhskohbo/no-captcha package. This library provides an easy way of integrating reCAPTCHA in Laravel.

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

composer require anhskohbo/no-captcha

Add the below line to the providers array in the config/app.php file.

Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,

In the same file, include the class alias in 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 to the following constants.

NOCAPTCHA_SECRET=
NOCAPTCHA_SITEKEY=

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 integrating reCAPTCHA. Now let’s write some code and make it into action.

Open the blade file having the HTML form. On top of the blade file initialize the JS source as follows:

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

Add the below 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 the HTML form with a few fields and add reCAPTCHA to the form using the code below.

{!! NoCaptcha::renderJs() !!}
 
@if ($errors->has('g-recaptcha-response'))
    <strong>{{ $errors->first('g-recaptcha-response') }}</strong>
@endif

<form action="{{ url('ROUTE_HERE') }}" method="post">
    @csrf
    <p>Name: <input type="text" name="fullname" required /></p>
    <p>Email: <input type="email" name="email" required /></p>
    <p>Message: <textarea name="message" required></textarea></p>
    {!! NoCaptcha::display() !!}
    <p><input type="submit" name="submit" value="Submit" /></p>
</form>

After adding the above code, you will see the “I’m not a robot” checkbox appear in something like the screenshot below.

I'm not a robot captcha

I have also added a code that displays an error if any 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 a Validator facade and validated a reCAPTCHA in the store() method. If it fails to validate, it will return back to view and throw an error.

That’s it! You have successfully added reCAPTCHA v2 with the 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 *