Laravel 5.5 - Google reCaptcha Code With Validation Example

Today, we are share with you in this article how to implement google reCaptcha code in laravel with validation. generally captcha use in register, login form and you can see in many website almost site use google reCaptcha. but you can also done this with manyally. but google captcha is best and many laravel package also available using that package you can easyly done this functionality in your application. anhskohbo/no-captcha laravel package is best for it and we are implementing google reCaptcha using this package.

In this tutorials we are implement google reCaptha in contactus form. but you can use it in any form.

After done this tutorials your output look like.

Why Use Captcha

In simple term captcha is use for stoping spam data. for example you have one simple form without add Captcha then some hackers may be add dummy data by looping. so, avoide this type spam activity in your side should Captcha is best option.

Install Package

First, we need to install anhskohbo/no-captcha package in your laravel application. simple run following command and install it.


composer require anhskohbo/no-captcha
	
Configure Package

After install successfully package we are should be configure this package service provider in config/app.php file.


'providers' => [
	....
	Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,
],

Set Google Key

Next, we neet to Google reCaptcha's site key and secret key. you can get keys form click on this link Google reCaptcha Amin. and get your keys.

After click on bellow link you can see following page.

If you want to test this demo in localhost. just put localhost as a domain name in domain section.

After submit this form then google redirect one another page and in this page you can show your Site key and Secret key

Now, open your .env file and set both of keys here.


NOCAPTCHA_SECRET=[secret-key]
NOCAPTCHA_SITEKEY=[site-key]	
	
Create Route

Next, open your web.php file and add following one route in it.


Route::get('contactus', 'ContactUsController@getContactus');
Route::post('contactus', 'ContactUsController@postContactus')->name('contactus');
	



Create Controller

Next, we have create ContactUsController.php controller in app/Http/Controllers folder. and also create getContactus() and postContactus() method in it.


namespace App\Http\Controllers;

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

class ContactUsController extends Controller
{    
    public function getContactus()
    {
        return view('contactus');
    }

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

        // Write here your database logic

        \Session::put('success', 'Youe Request Submited Successfully..!!');
        return redirect()->back();
    }
}
	
Core PHP Validation Code

If you integrated in core php then you can use following code for server side google recaptcha validation.


$secretKey = "Your-Secret-Key";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$input['g-recaptcha-response']."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {    
    // validation false message set here...
} else {
    // validation success message set here...
}	

Create Blade

Next, we have create contactus.blade.php file in resources/views/ folder.


@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Register</div>

                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="{{ route('contactus') }}">
                        {{ csrf_field() }}

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

                            <div class="col-md-6">
                                <input id="fullname" type="text" class="form-control" name="fullname" value="{{ old('fullname') }}" autofocus>
                                @if ($errors->has('fullname'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('fullname') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" 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('description') ? ' has-error' : '' }}">
                            <label for="description" class="col-md-4 control-label">description</label>

                            <div class="col-md-6">
                                <textarea id="description" class="form-control" name="description"></textarea>
                                @if ($errors->has('description'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('description') }}</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 pull-center">
                                {!! 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">
                                <button type="submit" class="btn btn-primary">
                                    Submit
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
	

Now we are ready to run our example so run bellow command ro quick run:


php artisan serve

Now you can open bellow URL on your browser:

	
http://localhost:8000/contactus

If you want to any problem then please write comment and also suggest for new topic for make tutorials in future. Thanks...

 Prev post

Next post