How to use Recaptcha In Form.

Hi everyone,
Today we shall learn how we can use ReCaptcha in laravel 6.0/7.0. You can simply use it in your project on form validation.It is quite easy. We will also use form validation in this tutorial.

It is very important for security purposes.It prevents hackers or other harmful objects and makes sure user is human. In other words, it authenticates the users and makes sure it is not a spider.

In this tutorial, you will learn how we can use ReCaptcha in form validation using mews/captcha laravel package. It is easy to follow and reliable for laravel packages.Without wasting our time let’s began to learn.Just Follow the steps:

Step 1:Download Laravel
Step 2:Install Recaptcha Package
Step 3: Configure Package
Step 4:Create Routes
Step 5:Create View
Step6: Create Controller
Step 7: Design Recaptcha view

Requirements

Following are the requirements.

php: ^7.2 
illuminate/config: ~5.0|^6.0|^7.0 
illuminate/filesystem: ~5.0|^6.0|^7.0 
illuminate/support: ~5.0|^6.0|^7.0 
illuminate/hashing: ~5.0|^6.0|^7.0 
illuminate/session: ~5.0|^6.0|^7.0 
intervention/image: ~2.5 
phpunit/phpunit: ^8.5 
mockery/mockery: ^1.0 

Step 1:Download Laravel

In the next step install laravel mes/captcha laravel packages. For this run following command to install laravel recaptcha package.

composer create-project --prefer-dist laravel/laravel blog

Step 2:Install Recaptcha Package

In the next step install laravel mes/captcha laravel packages.For this run following command to install laravel recaptcha package.

composer require mews/captcha 

Step 3: Configure Package

In the next step configure the packges in the config/app.php file using the following code.It will configure your package with the laravel application.

config/app.php 

'providers' => [ 
.... 
Mews\Captcha\CaptchaServiceProvider::class, 
], 
'aliases' => [ 
.... 
'Captcha' => Mews\Captcha\Facades\Captcha::class, 
], 

Step 4:Create Routes

Create rotues for validation of the form which you have to create.I created the following routes for this purpose

Route::get('re_captcha', 'HomeController@re_captcha')->name('re_captcha'); 
Route::post('validate_captcha', 'HomeController@validate_captcha')->name('validate_captcha'); 
Route::get('refresh_captcha', 'HomeController@refreshCaptcha')->name('refresh_captcha'); 

Step 5: Create View

create view re_captcha.blade.php in your laravel application or you can create your own view page which you like.

<html lang="en">
<head>
    <title>How to create captcha code in Laravel 5?</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="container" style="margin-top: 50px">
   <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
          <div class="panel-heading">Login</div>
          <div class="panel-body">
              <form class="form-horizontal" method="POST" action="{{ route('validate_captcha') }}">
                  {{ csrf_field() }}
                  <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="text" 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 for="password" class="col-md-4 control-label">Password</label>
                      <div class="col-md-6">
                          <input id="password" 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('captcha') ? ' has-error' : '' }}">
                      <label for="password" class="col-md-4 control-label">Captcha</label>
                      <div class="col-md-6">
                          <div class="captcha">
                          <span>{!! captcha_img() !!}</span>
                          <button type="button" class="btn btn-success btn-refresh" id="refresh"><i class="fa fa-refresh"></i></button>
                          </div>
                          <input id="captcha" type="text" class="form-control" placeholder="Enter Captcha" name="captcha">
                          @if ($errors->has('captcha'))
                              <span class="help-block">
                                  <strong>{{ $errors->first('captcha') }}</strong>
                              </span>
                          @endif
                      </div>
                  </div>
                 <div class="form-group">
                      <div class="col-md-8 col-md-offset-4">
                          <button type="submit" class="btn btn-primary">
                              Submit
                          </button>
                      </div>
                  </div>
              </form>
          </div>
      </div>
  </div>
</div>
</body>
<script type="text/javascript">
$("#refresh").click(function(){
  $.ajax({
     type:'GET',
     url:'/refresh_captcha',
     success:function(data){
        $(".captcha span").html(data.captcha);
     }
  });
});
</script>
</html>

Step 5:Create Controller

In this step you have to create controller .For this purpose create HomeController.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class HomeController extends Controller
{   
    public function re_captcha()
    {
        return view('re-captcha');
    }
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function validate_captcha(Request $request)
    {
        request()->validate([
            'email' => 'required|email',
            'password' => 'required',
            'captcha' => 'required|captcha'
        ],
        ['captcha.captcha'=>'Invalid captcha code.']);
        dd("Captcha Code Match :) .");
    }
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function refreshCaptcha()
    {
        return response()->json(['captcha'=> captcha_img('flat')]);
    }
}

Step 7: Design Recaptcha view

In the last step, we will create design our ReCaptcha. You can also use default ReCaptcha design. But I will create a custom ReCaptcha design. For this purpose run the following command on your composer.

php artisan vendor:publish 


Go to the config/captcha.php and copy the following code and paste. It will create a math captcha.

<?php

return [
    'default'   => [
        'length'    => 10,
        'width'     => 120,
        'height'    => 36,
        'quality'   => 90,
        'math'      => true, //Enable Math Captcha
    ],
    // ...
];

In this way, you can create ReCaptcha on your laravel application and prevent it from harmful factors of hackers.I hope you like the article.

One thought on “How to use Recaptcha In Form.

Leave a Reply

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