Create Captcha using Laravel

Captcha stands for Completely Automated Public Turing test. It is mainly used as a security test to ensure only human users can pass through. Computers or robots are not able of solving a captcha. There are different types of captcha we can use some protection. The logic behind why websites implement CAPTCHA codes into their registration processes is spam. In this example, we can use the mews captcha package to make a captcha.

Step 1: Install mews Captcha Package

Here, we have to add mews Captcha package so one your cmd or terminal and fire bellow command:

composer require mews/captcha

After successfully install package, open config/app.php file and add service provider and alias.

config/app.php

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

Step 3: Create Routes

here, we require to add three routes display login form, post login form and another for refresh captcha code. so open your routes/web.php file and add following route.

routes/web.php

Route::get('my-captcha', 'HomeController@myCaptcha')->name('myCaptcha');
Route::post('my-captcha', 'HomeController@myCaptchaPost')->name('myCaptcha.post');
Route::get('refresh_captcha', 'HomeController@refreshCaptcha')->name('refresh_captcha');

Step 4: Create HomeController Methods

Now we require to create HomeController and add new three methods as myCaptcha(), myCaptchaPost() and refreshCaptcha(). So let’s create controller and then put bellow code:

routes/web.php

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

Step 5: Create View File

At last step, we have to simple create myCaptcha.blade.php file and need to write code there for generate bootstrap login form, jquery ajax code. So let’s copy bellow code:

resources/views/myCaptcha.blade.php

<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('myCaptcha.post') }}">
 {{ 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"><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">

$(".btn-refresh").click(function(){

 $.ajax({

 type:'GET',

 url:'/refresh_captcha',

 success:function(data){

 $(".captcha span").html(data.captcha);

}

});

});

</script>

</html>

Now we are ready to run our captcha code example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/my-captcha

Leave a Reply

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