We have to use captcha in our form to prevent spam,bot etc. In this example am showing how to use google reCAPTCHA in laravel 5.2. Here i gonna use a package which is available in github anhskohbo/no-captcha
Before we start lets see what is CAPTCHA and reCAPTCHA?
CAPTCHA (Completely Automated Public Turing Test to tell Computers and Humans Apart) is a program that use for human verification or program which protect websites against bots, spam etc. Generally Captcha contain a image for human challenge on forms for human read and enter captcha image text.
reCAPTCHA is a free service from Google that helps protect websites from spam and abuse. A “CAPTCHA” is a test to tell human and bots apart. It is easy for humans to solve, but hard for “bots” and other malicious software to figure out. By adding reCAPTCHA to a site, you can block automated software while helping your welcome users to enter with ease.
Steps to add Google reCAPTCHA in Laravel 5.2
Before going to code let’s see what we will get as output.
view DEMO
Step 1
Add below code in composer.json
under 'require'
.
// composer.json
"require": {
.
.
"anhskohbo/no-captcha": "2.*",
},
Now open your terminal and run below command to get package from github.
// terminal
composer update
Step 2
Open the file app.php under config folder.
Add the following line under ‘providers’ array.
// app.php
'providers' => [
.
.
.
Anhskohbo\NoCaptcha\NoCaptchaServiceProvider::class,
],
Step 3
Get google reCAPTCHA site key and secret-key.
Click here to get those key
Now login with your gmail.
You will see a form like below.
Fill the form, give label and Domains then press register.
You will get site and secret key.
Step 4
Add those keys to .env file as follows
// .env
NOCAPTCHA_SECRET=[secret-key]
NOCAPTCHA_SITEKEY=[site-key]
Step 5
We have configured reCAPTCHA for laravel application.Now let’s integrate reCAPTCHA on our form.
Its very simple, copy the code and paste it inside form
tag.
// blade . . . {!! app('captcha')->display(); !!} . .
Bingo!! reCAPTCHA is displaying in our form.
Step 6
Validation part is simple.add below codes to your validating array.
// controller
$validator=Validator::make($request->all(),
array(
// rules
'g-recaptcha-response' => 'required|captcha',
)
);
Customizing the reCAPTCHA error message
Here is the custom message code
//controller
$validator=Validator::make($request->all(),
array(
// rules
'g-recaptcha-response' => 'required|captcha',
),
array(
// custom message
'g-recaptcha-response.required'=>'The captcha field is required.'
)
);
if($validator->fails()){
//return with error
return redirect()->back()->withErrors($validator)->withInput();
}else{
// do the stuff after validation success
}