AppDividend
Latest Code Tutorials

How to Generate Captcha Code in Laravel

233

How to Generate Captcha Code in Laravel is the topic, we will discuss today. 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 bots 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 because of spam. In this example, we can use mews captcha package for make captcha.

How to Generate Captcha Code in Laravel

First, we install Laravel Project.

Step 1: Configure Laravel Project

Install the brand new Laravel Project by the typing following command.

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

Step 2: Install Captcha package

Now, we have to add mews captcha package so switch to your terminal and type below command.

composer require mews/captcha

Step 3: Add Service Provider and aliases

To use the Captcha Service Provider, you must register the provider when bootstrapping your Laravel Project.

Find the providers in config >> app.php file and register the Captcha Service Provider.

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

Locate the aliases in config >> app.php file and register the aliases.

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

Step 4: Create one controller

php artisan make:controller CaptchaController --resource

It will create one controller file called CaptchaController.php file.

Define validation and captcha code in controller file.

Related Posts
1 of 26
//CaptchController.php

 public function create()
    {
        return view('captchacreate');
    }
    public function captchaValidate(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required|min:6',
            'captcha' => 'required|captcha'
        ]);
    }
    public function refreshCaptcha()
    {
        return response()->json(['captcha'=> captcha_img()]);
    }

In captchaValidate() function we have put the validation. If any validation fails it throws an error.

In refreshCaptcha() function we have defined the refresh code. When the user clicks on refresh, captcha code change.

Step 5: Define Routes 

We list route in routes  >>  web.php file. So let us do it.

//web.php

Route::get('createcaptcha', 'CaptchaController@create');
Route::post('captcha', 'CaptchaController@captchaValidate');
Route::get('refreshcaptcha', 'CaptchaController@refreshCaptcha');

In the web.php file, we define Three(3) routes the first route for display the login page, the second route for post request, and the third route for refresh captcha code.

Step 6: Create one view file

Create a file in the resources  >>  views  >>   captchacreate.blade.php and set the following code in it.

//captchacreate.blade.php

<html lang="en">
<head>
    <title>Captcha Code in Laravel</title>
    <link rel="stylesheet" href="{{asset('css/app.css')}}">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">   
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", rel="stylesheet", integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN", crossorigin="anonymous">
</head>
<body>
<div class="container">
      <h2>Captcha Code in Laravel</h2><br/>
      @if ($errors->any())
      <div class="alert alert-danger">
          <ul>
              @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
              @endforeach
          </ul>
      </div><br />
      @endif
      <form method="post" action="{{url('captcha')}}">
        @csrf
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <label for="Name">Name:</label>
            <input type="text" class="form-control" name="name">
          </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="Email">Email:</label>
              <input type="text" class="form-control" name="email">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
              <label for="Password">Password:</label>
              <input type="password" class="form-control" name="password">
            </div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
             <div class="captcha">
               <span>{!! captcha_img() !!}</span>
               <button type="button" class="btn btn-success"><i class="fa fa-refresh" id="refresh"></i></button>
               </div>
            </div>
        </div>
        <div class="row">
          <div class="col-md-4"></div>
            <div class="form-group col-md-4">
             <input id="captcha" type="text" class="form-control" placeholder="Enter Captcha" name="captcha"></div>
          </div>
        <div class="row">
          <div class="col-md-4"></div>
          <div class="form-group col-md-4">
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </div>
      </form>
    </div>
</body>

<script type="text/javascript">
$('#refresh').click(function(){
  $.ajax({
     type:'GET',
     url:'refreshcaptcha',
     success:function(data){
        $(".captcha span").html(data.captcha);
     }
  });
});
</script>
</html>

 

How to Generate Captcha Code in Laravel

Next, Begin Laravel Development server by hit following command.

php artisan serve

If we do not enter any fields or enter invalid captcha code then we will get the errors.

captcha validation tutorial using Laravel

 

Finally, Our How to Generate Captcha Code in Laravel is over. Thanks for taking.

Leave A Reply

Your email address will not be published.