Laravel 5.1 Auth CAPTCHA Example (BotDetect v3.0; deprecated)

Laravel Auth CAPTCHA Example demonstrates how to integrate Laravel Auth is used to authenticate users to your application.

First Time Here?

Check the BotDetect Laravel 5.1 Captcha Quickstart for key integration steps.

Alongside the Captcha image, the user is provided with an input field to retype the displayed characters. Depending on if the Captcha code entered matches the displayed one or not, a message stating the validation result is shown on the form.

The simple code showing the message in this example would of course be replaced with useful form processing code in a real world scenario.

The default in Laravel 5.1 ships an example to authenticate users that is used Laravel Auth, but no captcha image is created. Here's what we started:

First, we need to configure database connection with entering connection details into the config/database.php file.

Next, we need to create users and password_resets tables -- using Migrations.

To create that tables, run the following command in your application's root directory:

Files for this ('bd-captcha-laravel-5.1-examples') example are:

The files are available for download as a part of the BotDetect Captcha Laravel integration package.

Routing – /app/Http/routes.php

// Authentication routes...
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@postLogin');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

// Registration routes...
Route::get('auth/register', 'Auth\AuthController@getRegister');
Route::post('auth/register', 'Auth\AuthController@postRegister');

// Password routes...
Route::get('password/email', 'Auth\PasswordController@getEmail');
Route::post('password/email', 'Auth\PasswordController@postEmail');
Route::get('password/reset/{token}', 'Auth\PasswordController@getReset');
Route::post('password/reset/{token}', 'Auth\PasswordController@postReset');

In the code above we have registered the routes to handle the actions inside the AuthController and PasswordController.

View – /resources/views/app.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel Auth Example</title>
  <link href="{{ URL::asset('css/bootstrap.min.css') }}" type="text/css" 
    rel="stylesheet">

  <!-- include the BotDetect layout stylesheet -->
  @if (class_exists('CaptchaUrls'))
    <link href="{{ CaptchaUrls::LayoutStylesheetUrl() }}" type="text/css" 
      rel="stylesheet">
  @endif
</head>
<body>
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
          <span class="sr-only">Toggle Navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Laravel Auth</a>
      </div>

      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li><a href="/">Home</a></li>
        </ul>

        <ul class="nav navbar-nav navbar-right">
          @if (Auth::guest())
            <li><a href="{{ URL::to('auth/login') }}">Login</a></li>
            <li><a href="{{ URL::to('auth/register') }}">Register</a></li>
          @else
            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" 
                role="button" aria-expanded="false">
                  {{ Auth::user()->name }} <span class="caret"></span>
              </a>
              <ul class="dropdown-menu" role="menu">
                <li><a href="{{ URL::to('auth/logout') }}">Logout</a></li>
              </ul>
            </li>
          @endif
        </ul>
      </div>
    </div>
  </nav>

  @yield('content')

  <!-- Scripts -->
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
</body>
</html>

The above code is defining a Blade Layout. The app view needs to add the required stylesheet of the library.

View – /resources/views/auth/login.blade.php

@extends('app')

@section('content')
<div class="container-fluid">
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading">Login</div>
        <div class="panel-body">
          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <strong>Whoops!</strong> There were some problems with your input
              .<br><br>
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif

          <form class="form-horizontal" role="form" method="POST" 
            action="{{ URL::to('auth/login') }}">
            {!!csrf_field() !!}

            <div class="form-group">
              <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') }}">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label">Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control" name="password">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha image html-->
                {!! $captchaHtml !!}
              </div>
              <div class="col-md-6 col-md-offset-4">
              <!-- Captcha code user input textbox -->
                <input type="text" class="form-control" id="CaptchaCode" 
                  name="CaptchaCode" style="width: 276px; margin-top: 5px">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <div class="checkbox">
                  <label>
                    <input type="checkbox" name="remember"> Remember Me
                  </label>
                </div>
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary" style="margin-right: 15px;">
                  Login
                </button>

                <a href="{{ URL::to('password/email') }}">Forgot Your Password?</a>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

The above code to display authentication in a view, we output the variable $captchaHtml (set in, and passed by in the getLogin() action of the AuthController).

We have added Captcha Code input field to view. This Captcha Code input will be checked in the postLogin() action later.

Login page screenshot:

Laravel 5.1 Auth Login BotDetect Captcha validation screenshot

View – /resources/views/auth/register.blade.php

@extends('app')

@section('content')
<div class="container-fluid">
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading">Register</div>
        <div class="panel-body">
          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <strong>Whoops!</strong> There were some problems with your input
              .<br><br>
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif

          <form class="form-horizontal" role="form" method="POST" 
            action="{{ URL::to('auth/register') }}">
            {!!csrf_field() !!}

            <div class="form-group">
              <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') }}">
              </div>
            </div>

            <div class="form-group">
              <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') }}">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label">Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control" name="password">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label">Confirm Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control" 
                  name="password_confirmation">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha image html -->
                {!! $captchaHtml !!}
              </div>
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha code user input textbox -->
                <input type="text" class="form-control" id="CaptchaCode" 
                  name="CaptchaCode" style="width: 276px; margin-top: 5px">
              </div>
            </div>

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

The above code to display authentication in a view, we output the variable $captchaHtml (set in, and passed by in the getRegister() action of the UsersController).

We also added Captcha Code input field to view. This Captcha Code input will be checked in the postRegister() action later.

Register page screenshot:

Laravel 5.1 Auth Register BotDetect Captcha validation screenshot

View – /resources/views/auth/password.blade.php

@extends('app')

@section('content')
<div class="container-fluid">
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading">Reset Password</div>
        <div class="panel-body">
          @if (session('status'))
            <div class="alert alert-success">
              {{ session('status') }}
            </div>
          @endif

          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <strong>Whoops!</strong> There were some problems with your input
                .<br><br>
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif

          <form class="form-horizontal" role="form" method="POST" 
            action="{{ URL::to('password/email') }}">
            {!!csrf_field() !!}

            <div class="form-group">
              <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') }}">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha image html -->
                {!! $captchaHtml !!}
              </div>
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha code user input textbox -->
                <input type="text" class="form-control" id="CaptchaCode" 
                  name="CaptchaCode" style="width: 276px; margin-top: 5px">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary">
                  Send Password Reset Link
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

The above code to display authentication in a view, we output the variable $captchaHtml (set in, and passed by in the getEmail() action of the PasswordController).

We also added Captcha Code input field to view. This Captcha Code input will be checked in the postEmail() action later.

Send password page screenshot:

Laravel 5.1 Auth Send Password BotDetect Captcha validation screenshot

View – /resources/views/auth/reset.blade.php

@extends('app')

@section('content')
<div class="container-fluid">
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
        <div class="panel-heading">Reset Password</div>
        <div class="panel-body">
          @if (count($errors) > 0)
            <div class="alert alert-danger">
              <strong>Whoops!</strong> There were some problems with your input.<br><br>
              <ul>
                @foreach ($errors->all() as $error)
                  <li>{{ $error }}</li>
                @endforeach
              </ul>
            </div>
          @endif

          <form class="form-horizontal" role="form" method="POST" action="{{ URL::to('password/reset/' . $token) }}">
            {!! csrf_field() !!}
            <input type="hidden" name="token" value="{{ $token }}">

            <div class="form-group">
              <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') }}">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label">Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control" name="password">
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-4 control-label">Confirm Password</label>
              <div class="col-md-6">
                <input type="password" class="form-control" name="password_confirmation">
              </div>
            </div>
              
            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha image html -->
                {!! $captchaHtml !!}
              </div>
              <div class="col-md-6 col-md-offset-4">
                <!-- Captcha code user input textbox -->
                <input type="text" class="form-control" id="CaptchaCode" name="CaptchaCode" style="width: 276px; margin-top: 5px">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn btn-primary">
                  Reset Password
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
@endsection

The above code to display authentication in a view, we output the variable $captchaHtml (set in, and passed by in the getReset() action of the PasswordController).

We also added Captcha Code input field to view. This Captcha Code input will be checked in the postReset() action later.

Reset password page screenshot:

Laravel 5.1 Auth Reset Password BotDetect Captcha validation screenshot

Controller – /app/Http/Controllers/Auth/AuthController.php

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use App\Http\Controllers\Controller;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
// Importing the BotDetectCaptcha class
use LaravelCaptcha\Integration\BotDetectCaptcha;

class AuthController extends Controller
{
  /*
  |--------------------------------------------------------------------------
  | Registration & Login Controller
  |--------------------------------------------------------------------------
  |
  | This controller handles the registration of new users, as well as the
  | authentication of existing users. By default, this controller uses
  | a simple trait to add these behaviors. Why don't you explore it?
  |
  */

  use AuthenticatesAndRegistersUsers, ThrottlesLogins;

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

  /**
   * 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']),
    ]);
  }

  /**
   * Get captcha instance to handle for the login page.
   * 
   * @return object
   */
  private function getLoginCaptchaInstance()
  {
    // Captcha parameters:
    $captchaConfig = [
      'CaptchaId' => 'LoginCaptcha', // a unique Id for the Captcha instance
      'UserInputId' => 'CaptchaCode', // Id of the Captcha code input textbox
      // The path of the Captcha config file is inside the config folder
      'CaptchaConfigFilePath' => 'captcha_config/LoginCaptchaConfig.php'
    ];
    return BotDetectCaptcha::GetCaptchaInstance($captchaConfig);
  }

  /**
   * Show the application login form.
   *
   * @return \Illuminate\Http\Response
   */
  public function getLogin()
  {
    // captcha instance of the login page
    $captcha = $this->getLoginCaptchaInstance();
    
    if (view()->exists('auth.authenticate')) {
      return view('auth.authenticate', ['captchaHtml' => $captcha->Html()]);
    }

    return view('auth.login', ['captchaHtml' => $captcha->Html()]);
  }
  
  /**
   * Handle a login request to the application.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function postLogin(Request $request)
  {
    $this->validate($request, [
      $this->loginUsername() => 'required', 'password' => 'required', 'CaptchaCode' => 'required',
    ]);

    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    $throttles = $this->isUsingThrottlesLoginsTrait();

    if ($throttles && $this->hasTooManyLoginAttempts($request)) {
      return $this->sendLockoutResponse($request);
    }
    
    // captcha instance of the login page
    $captcha = $this->getLoginCaptchaInstance();

    // validate the user-entered Captcha code when the form is submitted
    $code = $request->input('CaptchaCode');
    $isHuman = $captcha->Validate($code);
    
    if ($isHuman) {
      $credentials = $this->getCredentials($request);

      if (Auth::attempt($credentials, $request->has('remember'))) {
        return $this->handleUserWasAuthenticated($request, $throttles);
      }
      
      // If the login attempt was unsuccessful we will increment the number of attempts
      // to login and redirect the user back to the login form. Of course, when this
      // user surpasses their maximum number of attempts they will get locked out.
      if ($throttles) {
        $this->incrementLoginAttempts($request);
      }
    }
   
    return redirect($this->loginPath())
        ->withInput($request->only($this->loginUsername(), 'remember'))
        ->withErrors([
            $this->loginUsername() => $this->getFailedLoginMessage(),
            'CaptchaCode' => 'Wrong code. Try again please.'
        ]);
  }
  
  /**
   * Get captcha instance to handle for the register page
   * 
   * @return object
   */
  private function getRegisterCaptchaInstance()
  {
    // Captcha parameters:
    $captchaConfig = [
      'CaptchaId' => 'RegisterCaptcha', // a unique Id for the Captcha instance
      'UserInputId' => 'CaptchaCode', // Id of the Captcha code input textbox
       // The path of the Captcha config file is inside the config folder
      'CaptchaConfigFilePath' => 'captcha_config/RegisterCaptchaConfig.php'
    ];
    return BotDetectCaptcha::GetCaptchaInstance($captchaConfig);
  }
  
  /**
   * Show the application registration form.
   *
   * @return \Illuminate\Http\Response
   */
  public function getRegister()
  {
    // captcha instance of the register page
    $captcha = $this->getRegisterCaptchaInstance();

    // passing Captcha Html to register view
    return view('auth.register', ['captchaHtml' => $captcha->Html()]);
  }
  
  /**
   * Handle a registration request for the application.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function postRegister(Request $request)
  {
    $validator = $this->validator($request->all());
    
    // captcha instance of the register page
    $captcha = $this->getRegisterCaptchaInstance();

    // validate the user-entered Captcha code when the form is submitted
    $code = $request->input('CaptchaCode');
    $isHuman = $captcha->Validate($code);
    
    if (!$isHuman || $validator->fails()) {
      if (!$isHuman) {
        $validator->errors()->add('CaptchaCode', 'Wrong code. Try again please.');
      }
      
      return redirect()
              ->back()
              ->withInput()
              ->withErrors($validator->errors());
    }

    Auth::login($this->create($request->all()));

    return redirect($this->redirectPath());
  }
  
}

The Controller part of the example provides necessary helpers and data used by View, and adds the Captcha validation functionality as outlined in the BotDetect Laravel 5.1 integration guide.

The code above is that we are overridden the AuthenticatesAndRegistersUsers trait of the Laravel.

After creating two functions to get an instance of the Captcha class for each page called getRegisterCaptchaInstance() and getLoginCaptchaInstance(), on a HTTP GET request the getRegister(), and the getLogin() actions pass the generated Captcha Html to View by pass an array of data as the second parameter to the view view helper (or you can also use the with() method).

Method: postRegister()

On HTTP POST request (user submit), the postRegister() action executes and we validate user entered data using the Validation class and validate Captcha Code with the Validate() method of the $captcha object.

Method: postLogin()

On HTTP POST request (user submit), the postLogin() action executes and we check user's email and password using the Auth::attempt() and validate Captcha Code with the Validate() method of the $captcha object.

Controller – /app/Http/Controllers/Auth/PasswordController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Password;
// Importing the BotDetectCaptcha class
use LaravelCaptcha\Integration\BotDetectCaptcha;

class PasswordController extends Controller
{
  /*
  |--------------------------------------------------------------------------
  | Password Reset Controller
  |--------------------------------------------------------------------------
  |
  | This controller is responsible for handling password reset requests
  | and uses a simple trait to include this behavior. You're free to
  | explore this trait and override any methods you wish to tweak.
  |
  */

  use ResetsPasswords;

  /**
   * Create a new password controller instance.
   *
   * @return void
   */
  public function __construct()
  {
    $this->middleware('guest');
  }
  
  /**
   * Get captcha instance to handle for the email page
   * 
   * @return object
   */
  private function getEmailCaptchaInstance() 
  {
    // Captcha parameters:
    $captchaConfig = [
      'CaptchaId' => 'Captcha', // a unique Id for the Captcha instance
      'UserInputId' => 'CaptchaCode', // Id of the Captcha code input textbox
       // The path of the Captcha config file is inside the config folder
      'CaptchaConfigFilePath' => 'captcha_config/EmailCaptchaConfig.php'
    ];
    return BotDetectCaptcha::GetCaptchaInstance($captchaConfig);
  }
  
  /**
   * Display the form to request a password reset link.
   *
   * @return \Illuminate\Http\Response
   */
  public function getEmail()
  {
    // captcha instance of the email page
    $captcha = $this->getEmailCaptchaInstance();
    
    return view('auth.password', ['captchaHtml' => $captcha->Html()]);
  }

  /**
   * Send a reset link to the given user.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function postEmail(Request $request)
  {
    $this->validate($request, [
      'email' => 'required|email',
      'CaptchaCode' => 'required'
    ]);
    
    // captcha instance of the email page
    $captcha = $this->getEmailCaptchaInstance();

    // validate the user-entered Captcha code when the form is submitted
    $code = $request->input('CaptchaCode');
    $isHuman = $captcha->Validate($code);
    
    if ($isHuman) {
      $response = Password::sendResetLink($request->only('email'), function (Message $message) {
        $message->subject($this->getEmailSubject());
      });

      switch ($response) {
        case Password::RESET_LINK_SENT:
          return redirect()->back()->with('status', trans($response));

        case Password::INVALID_USER:
          return redirect()->back()->withErrors(['email' => trans($response)]);
      }
    } 
  
    return redirect()
            ->back()
            ->withErrors(['CaptchaCode' => 'Wrong code. Try again please.']);
  }
  
  /**
   * Get captcha instance to handle for the reset password page
   * 
   * @return object
   */
  private function getResetPasswordCaptchaInstance() 
  {
    // Captcha parameters:
    $captchaConfig = [
      'CaptchaId' => 'ResetPasswordCaptcha', // a unique Id for the Captcha instance
      'UserInputId' => 'CaptchaCode', // Id of the Captcha code input textbox
       // The path of the Captcha config file is inside the config folder
      'CaptchaConfigFilePath' => 'captcha_config/ResetPasswordCaptchaConfig.php'
    ];
    return BotDetectCaptcha::GetCaptchaInstance($captchaConfig);
  }
  
  /**
   * Display the password reset view for the given token.
   *
   * @param  string  $token
   * @return \Illuminate\Http\Response
   */
  public function getReset($token = null)
  {
    if (is_null($token)) {
      throw new NotFoundHttpException;
    }
    // captcha instance of the reset password page
    $captcha = $this->getResetPasswordCaptchaInstance();
 
    return view('auth.reset')
            ->with('token', $token)
            ->with('captchaHtml', $captcha->Html());
  }
  
  /**
   * Reset the given user's password.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function postReset(Request $request)
  {
    $this->validate($request, [
      'token' => 'required',
      'email' => 'required|email',
      'password' => 'required|confirmed',
      'CaptchaCode' => 'required'
    ]);
    
    // captcha instance of the reset password page
    $captcha = $this->getResetPasswordCaptchaInstance();

    // validate the user-entered Captcha code when the form is submitted
    $code = $request->input('CaptchaCode');
    $isHuman = $captcha->Validate($code);

    if ($isHuman) {
      $credentials = $request->only(
        'email', 'password', 'password_confirmation', 'token'
      );

      $response = Password::reset($credentials, function ($user, $password) {
        $this->resetPassword($user, $password);
      });

      switch ($response) {
          case Password::PASSWORD_RESET:
            return redirect($this->redirectPath());

          default:
            return redirect()->back()
                          ->withInput($request->only('email'))
                          ->withErrors(['email' => trans($response)]);
      }
    }
    
    return redirect()
            ->back()
            ->withErrors(['CaptchaCode' => 'Wrong code. Try again please.']);
  }
}

The Controller part of the example provides necessary helpers and data used by View, and adds the Captcha validation functionality as outlined in the BotDetect Laravel 5.1 integration guide.

The code above is that we are overridden the ResetsPasswords trait of the Laravel.

After creating a function to get an instance of the Captcha class called getEmailCaptchaInstance(), and getResetPasswordCaptchaInstance() on a HTTP GET request the getEmail(), and the getReset() actions pass the generated Captcha Html to View by pass an array of data as the second parameter to the view view helper (or you can also use the with() method).

Method: postEmail()

On HTTP POST request (user submit), the postEmail() action executes and we validate user entered data using the Validation class and validate Captcha Code with the Validate() method of the $captcha object.

Method: postReset()

On HTTP POST request (user submit), the postReset() action executes and we validate user entered data using the Validation class and validate Captcha Code with the Validate() method of the $captcha object.

Captcha configuration options – /config/captcha_config/LoginCaptchaConfig.php

<?php if (!class_exists('CaptchaConfiguration')) { return; }
  
// BotDetect PHP Captcha configuration options

$LBD_CaptchaConfig = CaptchaConfiguration::GetSettings();

$imageStyles = array(
  ImageStyle::Chipped, 
  ImageStyle::Negative, 
);
$LBD_CaptchaConfig->ImageStyle = CaptchaRandomization::GetRandomImageStyle($imageStyles);

In the code above, we have overridden the default settings of library for the login page. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

Captcha configuration options – /config/captcha_config/RegisterCaptchaConfig.php

<?php if (!class_exists('CaptchaConfiguration')) { return; }

// BotDetect PHP Captcha configuration options

$LBD_CaptchaConfig = CaptchaConfiguration::GetSettings();

$LBD_CaptchaConfig->CodeLength = 6;
$LBD_CaptchaConfig->ImageWidth = 250;
$LBD_CaptchaConfig->ImageHeight = 50;

In the code above, we have overridden the default settings of library for the register page. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

Captcha configuration options – /config/captcha_config/ResetPasswordCaptchaConfig.php

<?php if (!class_exists('CaptchaConfiguration')) { return; }

// BotDetect PHP Captcha configuration options

$LBD_CaptchaConfig = CaptchaConfiguration::GetSettings();

$LBD_CaptchaConfig->CodeLength = CaptchaRandomization::GetRandomCodeLength(3, 5);
$LBD_CaptchaConfig->ImageWidth = 250;
$LBD_CaptchaConfig->ImageHeight = 50;

In the code above, we have overridden the default settings of library for the send password page. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

Captcha configuration options – /config/captcha_config/ResetPasswordCaptchaConfig.php

<?php if (!class_exists('CaptchaConfiguration')) { return; }

// BotDetect PHP Captcha configuration options

$LBD_CaptchaConfig = CaptchaConfiguration::GetSettings();

$LBD_CaptchaConfig->CodeLength = CaptchaRandomization::GetRandomCodeLength(3, 4);
$LBD_CaptchaConfig->ImageWidth = 250;
$LBD_CaptchaConfig->ImageHeight = 50;

In the code above, we have overridden the default settings of library for the reset password page. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.



Please Note

The information on this page is out of date and applies to a deprecated version of BotDetect™ CAPTCHA (v3.0).

An up-to-date equivalent page for the latest BotDetect Captcha release (v4) is BotDetect v4 Captcha documentation index.

General information about the major improvements in the current BotDetect release can be found at the What's New in BotDetect v4.0 page.