Md Obydullah Howdy, I am Md Obydullah. I love to write the article which may help others. It's my passion.

Integrate Google reCAPTCHA v2 in Laravel with Validation

Published on May 7, 2019 3 min read

Google ReCaptcha is a captcha like a system, that provides security against hackers and sticks or CURL requests. It’s very popular. Today we will add “I’m not a robot” captcha in the contact form of our Laravel application.

Table of Contents

  1. Install Laravel and Basic Configurations
  2. Install anhskohbo/no-captcha Package
  3. Get Google reCAPTCHA API Key
  4. Create a Controller
  5. Create a Blade File
  6. Register Routes
  7. Run and Test

Step 1 : Install Laravel and Basic Configurations

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Step 2 : Install anhskohbo/no-captcha Package

For recaptcha we are going to use anhskohbo/no-captcha package. Let’s install this via artisan command:

composer require anhskohbo/no-captcha

If you’re using Laravel 5.5 and above, you don’t need to manual configuration. I am writing the manual configuration for those people who are using Laravel 5.4 or more previous version.

In config/app.php add the following:

app.php
'providers' => [
     .....
     Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,
 ],
 'aliases' => [
     .....
     'NoCaptcha' => Anhskohbo\NoCaptcha\Facades\NoCaptcha::class,
 ]

Now publish the vendor by this command:

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

Step 3 : Get Google reCAPTCHA API Key

We have to create a Google reCAPTCHA project. Visit reCAPTCHA admin panel and create a project. Select version 2.

Then hit submit button to get the site and secret key like this:

Now open .env file and put site and secret key in this two variables:

.env
NOCAPTCHA_SITEKEY=site_key
NOCAPTCHA_SECRET=secret_key

Step 4 : Create a Controller

Let’s create a controller named “ContactFormController” by typing this command:

php artisan make:controller ContactFormController

Open the controller from app>Http>Controllers and paste this code:

ContactFormController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ContactFormController extends Controller
{

    public function form()
    {
        return view('contactfrom');
    }

    public function contactRequest(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required',
            'g-recaptcha-response' => 'required|captcha',
        ]);

        // send email
        return "Email has been sent. We will reply you soon.";
    }
}

Step 5 : Create a Blade File

To view the contact form, we need a view file. Go to resources>views folder and create a folder named “contactfrom.blade.php”. Then open the file and paste this code:

contactfrom.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Google reCAPTCHA v2</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    {!! NoCaptcha::renderJs() !!}
</head>
<body>
<div class="container" style="margin-top: 50px; width: 750px;">
    <div class="card card-primary">
        <div class="card-body">
            <h4 class="card-title text-center">Google reCAPTCHA v2</h4>
            <form class="form-horizontal" role="form" method="POST" action="{{ route('contact-request') }}">
                {!! csrf_field() !!}

                <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                    <label class="col-md-4 control-label">Name</label>
                    <div class="col-md-12">
                        <input type="text" class="form-control" name="name" value="{{ old('name') }}">
                        @if ($errors->has('name'))
                            <span class="help-block text-danger">
                                <strong>{{ $errors->first('name') }}</strong>
                            </span>
                        @endif
                    </div>
                </div>

                <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                    <label class="col-md-4 control-label">E-Mail Address</label>
                    <div class="col-md-12">
                        <input type="email" class="form-control" name="email" value="{{ old('email') }}">
                        @if ($errors->has('email'))
                            <span class="help-block text-danger">
                                <strong>{{ $errors->first('email') }}</strong>
                            </span>
                        @endif
                    </div>
                </div>

                <div class="form-group{{ $errors->has('message') ? ' has-error' : '' }}">
                    <label class="col-md-4 control-label">Message</label>
                    <div class="col-md-12">
                        <textarea class="form-control" name="message" rows="3">{{ old('message') }}</textarea>
                        @if ($errors->has('message'))
                            <span class="help-block text-danger">
                                <strong>{{ $errors->first('message') }}</strong>
                            </span>
                        @endif
                    </div>
                </div>

                <div class="form-group{{ $errors->has('g-recaptcha-response') ? ' has-error' : '' }}">
                    <label class="col-md-4 control-label">Captcha</label>
                    <div class="col-md-12">
                        {!! app('captcha')->display() !!}
                        @if ($errors->has('g-recaptcha-response'))
                            <span class="help-block text-danger">
                                <strong>{{ $errors->first('g-recaptcha-response') }}</strong>
                            </span>
                        @endif
                    </div>
                </div>

                <div class="form-group">
                    <div class="col-md-6 col-md-offset-4">
                        <br/>
                        <button type="submit" class="btn btn-primary">
                            Contact
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Step 6 : Register Routes

We have created two methods in the ContactFormController. Let’s define two routes for the two methods. Open routes/web.php and paste this code:

web.php
<?php

Route::get('contact', 'ContactFormController@form');
Route::post('contact-request', 'ContactFormController@contactRequest')->name('contact-request');

Step 7 : Run and Test

We have completed all the tasks. It’s time to test. Now run the project and visit this route:

http://localhost:8000/contact

You will see the output like this:

We have added validation too.

We have successfully integrated Google reCAPTCHA v2 in our project. 🙂

You're welcome to suggest any article to write!

Md Obydullah Howdy, I am Md Obydullah. I love to write the article which may help others. It's my passion.

Leave a Reply

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