Laravel 5- Google reCaptcha integration and validation example

By | May 27, 2018

Hi guys, In this article i am going to tell you about laravel5- google reCaptcha integration and validation example. If you want to secure you application’s form then captcha is a good choice to secure a form submission in your application. And google reCaptcha is best for that.

If you do not secure you form through captcha then anyone send post request with malicious data to your server from anywhere or through curl request which could be dangerous for your database or application.

In this article we will use anhskohbo/no-captcha package of laravel. I am using this package because of its popularity. And there are simple step to integrate this into your application. Please follow the steps below.

Step 1: Installation

In this first step we will install this anhskohbo/no-captcha package into our laravel application through the command below. Run this command in your terminal or command prompt.

composer require anhskohbo/no-captcha

It will copy the required files in your application. After the running above command open config/app.php file and copy the below line of code to configure the package.

config/app.php

return [

  ......

  $provides => [

    ......

    ......,

    Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class

  ],

  .....

]

Step2: Get google site key and secret key from google account

In this step we will get google site key and secret key for google account. If you don’t have thee key. You can generate it from here Recaptcha Admin

It would open a form to register with the data like label and site on which you will implement the reCaptcha like the screenshot below-

After registering you will get site key and secret key like this

Step 3: Add Route

After getting these keys you will have to put this to .env file of your application in the form of two variables

.env

 

NOCAPTCHA_SECRET=[secret-key]

NOCAPTCHA_SITEKEY=[site-key]

Step 3: Add Route

In this step we will add required route. So open app/Http/routes.php file and copy the code below –

Route::get('site-register', 'Auth\AuthController@siteRegister');
Route::post('site-register', 'Auth\AuthController@siteRegisterPost');

Step 4: Add Controller Method

In this step we will add two methods in Auth Controller to handle the request. You just need to copy the code below into your AuthController.php file.

app/Http/Controllers/Auth/AuthController.php

namespace App\Http\Controllers\Auth;


use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
use Illuminate\Http\Request;


class AuthController extends Controller
{


    use AuthenticatesAndRegistersUsers, ThrottlesLogins;


    protected $redirectTo = '/';


    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }


    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }


    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }


    public function siteRegister()
    {
        return view('siteRegister');
    }


    public function siteRegisterPost(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required|same:password_confirmation',
            'password_confirmation' => 'required',
            'g-recaptcha-response' => 'required|captcha',
        ]);
        echo done;
    }
}

After adding the methods in controller lets go ahead for a view where this reCaptcha will be visible.

Step 5: Add Blade file

In this fifth and last step we will create a view file let’s give a name siteRegister.php where forms fields with google reCaptcha will be visible.

resources/views/siteRegister.blade.php

@extends('layouts.app')


@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-primary">
                <div class="panel-heading">Register</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="{{ url('/site-register') }}">
                        {!! csrf_field() !!}


                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Name</label>
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="name" value="{{ old('name') }}">
                                @if ($errors->has('name'))
                                    <span class="help-block">
                                        <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-6">
                                <input type="email" class="form-control" name="email" value="{{ old('email') }}">


                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>


                        <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Password</label>


                            <div class="col-md-6">
                                <input type="password" class="form-control" name="password">


                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>


                        <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Confirm Password</label>


                            <div class="col-md-6">
                                <input type="password" class="form-control" name="password_confirmation">


                                @if ($errors->has('password_confirmation'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password_confirmation') }}</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-6">
                                {!! app('captcha')->display() !!}


                                @if ($errors->has('g-recaptcha-response'))
                                    <span class="help-block">
                                        <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">
                                    <i class="fa fa-btn fa-user"></i>Register
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection