Vlad Hill


Web Development, Web Design, Graphic Design, Systems Administration

Installation Google reCAPTCHA on application forms based on the Laravel 5.4

This article about how we can to use thGoogle reCAPTCHA in Laravel for html form validation.

Prerequisites

  • You have isntalled web application runned under framework Laravel 5.4.
  • In our application there is Contact page with html form, which should be applied captcha to.

Step 1: Getting Packages

Install necessary packages using Composer:

$ composer require "laravelcollective/html":"^5.4.0"
$ composer require anhskohbo/no-captcha

Step 2: Configuration

We are going to edit the app.php file.

$ joe config/app.php

Now we add to the end of section "providers" next two rows:

'providers' => [
// ...
Collective\Html\HtmlServiceProvider::class,
Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class
// ...
],

And to the end of  “aliases” section add:

'aliases' => [
// ...
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
// ...
],

Such means necessary service providers will be allowed to us by:

use Form;
use Html;

Step 3: Setting up Site and Secret Keys

To get site and secret keys we should visit https://www.google.com/recaptcha, fill and send next form:

As result after click by button Register we will grab our “secret key” and “site key”.

Next make changes in the .env file by:

$ joe .env

and add next two rows, replacing SECRET_KEY and SITE_KEY with real values:

NOCAPTCHA_SECRET= SECRET_KEY
NOCAPTCHA_SITEKEY= SITE_KEY

Step 4: Setting up Validation Rule

We should add validation rule for captcha to client-side validation form.

In my case, I use reCAPTCHA on the created Contact page. My applicaiton based on the repositories and validation rules for Contact page is on the app\Http\Requests\ContactRequest.php file.

Add next row to the end of validation array

public function rules()
{
  return [
    // ...
	'g-recaptcha-response' => 'required|captcha'
	];
}

Step 5: Adding Captcha to the View

Let’s add reCAPTCHA to the Contact form.

Open contact page view by path /resources/views/front/contact.blade.php and add next rows into the end of the html form (before Form::close() tag):

// ...
  {!! app('captcha')->display()!!}							   
  {!! $errors->first('g-recaptcha-response',':message') !!}							   
// ...

References

 https://www.google.com/recaptcha/intro/

https://github.com/google/recaptcha


Comments

You must be loged to add a comment !