Generate Captcha code and Validation by using BotDetect package in laravel

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Some days ago I was think we should use the captcha code on our registration form because of captcha code prevent from spams, bots etc. Today now in this post i will show you how to Generate Captcha code and Validation by using BotDetect package in laravel. Most of the our application we need to use the captcha verification because it is very important for the security reason. There are also several library to generate the captcha image in Laravel application.

So now In this example i will use BotDetect package library for the generate captcha image and by using their validation. we know BotDetect is a very popular library and also very customize library. They are provide us several ui design for the captcha code and also how much character do you want? We can set all the thing by using this package.

So now in this post i will give you a very simple example from scratch for generate captcha code image as we can also see the bellow preview. After the complete this example we can found the ui design , Just we need to just follow the few step and find your result:

Step 1: Installation

Today now in first step we will install a new package captcha-com/laravel-captcha for generate the captcha code image. We know this package through we can generate the captcha code image for our project. So at first fire the bellow command in your cmd or terminal:

composer require captcha-com/laravel-captcha:"4.*"

Now we have to add the provider path and alias path in our config/app.php file so need to open that file and then add the bellow code.

config/app.php

return [
	......
	$provides => [
		......
		......,
		LaravelCaptcha\Providers\LaravelCaptchaServiceProvider::class
	],
	.....
]

Okay now we will run the bellow command that way it will the generate app/captcha.php file for configuration and we can change and customize it very easily.

php artisan vendor:publish
Step 2: Add Route

Today now we are in second step we will add new two route for the creating small example on that way we can understand very well. So at first need to add the bellow route in your routes.php file.

app/Http/routes.php

Route::get('web-register', 'Auth\[email protected]');
Route::post('web-register', 'Auth\[email protected]');
Step 3: Add Controller Method

Now in this step we will add two method webRegister() and webRegisterPost() in AuthController Controller file for our the example. If we want to copy the whole controller file then also you can just need to copy and paste.

app/Http/Controllers/Auth/AuthController.php

namespace App\Http\Controllers\Auth;


use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
use Illuminate\Http\Request;


class AuthController extends Controller
{

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    protected $redirectTo = '/';

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }


    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|confirmed|min:6',
        ]);
    }


    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }


    public function webRegister()
    {
        return view('webRegister');
    }


    public function webRegisterPost(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required|same:password_confirmation',
            'password_confirmation' => 'required',
            'CaptchaCode' => 'required|valid_captcha'
        ]);
        print('write your other code here.');
    }
}
Step 4: Add Blade file

Now we are in the last step and we have to just create a new blade file webRegister.blade.php and need to put the bellow code on that file.

resources/views/webRegister.blade.php

@extends('layouts.app')


@section('content')
<link href="{{ captcha_layout_stylesheet_url() }}" type="text/css" rel="stylesheet">
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-primary">
                <div class="panel-heading">Register</div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" method="POST" action="{{ url('/web-register') }}">
                        {!! csrf_field() !!}


                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                            <label class="col-md-4 control-label">Name</label>
                            <div class="col-md-6">
                                <input type="text" class="form-control" name="name" value="{{ old('name') }}">
                                @if ($errors->has('name'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('name') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>


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


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


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


                            <div class="col-md-6">
                                <input type="password" class="form-control" name="password_confirmation">


                                @if ($errors->has('password_confirmation'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('password_confirmation') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>


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


                            <div class="col-md-6">
                                {!! captcha_image_html('ContactCaptcha') !!}
                                <input class="form-control" type="text" id="CaptchaCode" name="CaptchaCode" style="margin-top:5px;">


                                @if ($errors->has('CaptchaCode'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('CaptchaCode') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>


                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <br/>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fa fa-btn fa-user"></i>Register
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Read Also : Laravel Toastr Notifications Example

Try this.. if you want to more custom captcha then you can do from here : captcha.com.

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →