Laravel 4.2 Form Validation BotDetect CAPTCHA Example (BotDetect v3.0; deprecated)

First Time Here?

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

Laravel Form Validation BotDetect CAPTCHA Example shows how to integrate validation class

The brief example is based around a contact form which sends email if the user input is considered valid – a likely real world scenario for Captcha protection integration.

BotDetect Laravel 4.2 CAPTCHA Form Captcha validation screenshot

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

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

Routing – /app/routes.php

Route::get('contact', 'ContactController@getContact');
Route::post('contact', 'ContactController@postContact');

In the code above we have registered HTTP GET and POST verbs for the example page. On HTTP GET request to the example page, the getContact() action of the ContactController is executed, while on a HTTP POST request to the example page, the postContact() action of the ContactController is executed.

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

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Laravel Form Validation BotDetect CAPTCHA Example</title>
    {{ HTML::style('css/bootstrap.min.css') }}

    <!-- include the BotDetect layout stylesheet -->
    {{ HTML::style(CaptchaUrls::LayoutStylesheetUrl()) }}

    <style type="text/css">
        body { padding: 70px 0 }
        .container{ width: 980px !important }
        .error { color: red }
    </style>
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">BotDetect Captcha</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
          <ul class="nav navbar-nav navbar-right">
              <li>{{ HTML::link('example', 'Basic Example') }}</li>   
              <li>{{ HTML::link('contact', 'Form Example') }}</li>  
          </ul>
        </div><!--/.nav-collapse -->
      </div>
    </nav>

    <div class="container">
      <h2>Laravel Form Validation BotDetect CAPTCHA Example</h2><hr>

        @if (Session::has('status'))
          <div class="alert alert-success">
            {{ Session::get('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::open(array('url' => 'contact')) }}
        <div class="form-group">
            {{ Form::label('name', 'Name') }}
            {{ Form::text('name', Input::old('name'), array(
                    'class' => 'form-control'
                ))
             }}
          </div>

          <div class="form-group">
            {{ Form::label('email', 'Email') }}
            {{ Form::text('email', Input::old('email'), array(
                        'class' => 'form-control'
                    ))
                }}
          </div>

          <div class="form-group">
            {{ Form::label('subject', 'Subject') }}
            {{ Form::text('subject', Input::old('subject'), array(
                        'class' => 'form-control'
                    )) 
                }}
          </div>

          <div class="form-group">
            {{ Form::label('message', 'Message') }}
            {{ Form::textarea('message', Input::old('message'), array(
                        'class' => 'form-control'
                    )) 
                }}
          </div>

            <div class="form-group">
                <!-- Captcha image html-->
                {{ $captchaHtml }}
            </div>

            <div class="row">
                <div class="form-group col-sm-4">
                    {{ Form::label('CaptchaCode', 'Retype the characters from the picture') }}

                    <!-- Captcha code user input textbox -->
                    {{ Form::text('CaptchaCode', null, array(
                          'id' => 'CaptchaCode',
                          'class' => 'form-control'
                      ))
                    }}
                </div>
            </div>

        {{ Form::submit('Send', array('class' => 'btn btn-primary')) }}      

      {{ Form::close() }}
    </div>
</body>
</html>

The View part of this example is straightforward. The Laravel Forms & HTML and the Blade syntax are used to create a simple form. The Captcha related Html is placed above the Captcha code form input field.

Controller – /app/controllers/ContactController.php

<?php

// Importing the BotDetectCaptcha class
use LaravelCaptcha\Integration\BotDetectCaptcha;

class ContactController extends BaseController {

  // get a captcha instance to handle for the contact page
  private function getContactCaptchaInstance() {
    // Captcha parameters
    $captchaConfig = [
      'CaptchaId' => 'ContactCaptcha', // 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/ContactCaptchaConfig.php', 
    ];
    return BotDetectCaptcha::GetCaptchaInstance($captchaConfig);
  }

  public function getContact() {
    // captcha instance of the contact page
    $captcha = $this->getContactCaptchaInstance();

    // passing Captcha Html to contact view
    return View::make('contact', array('captchaHtml' => $captcha->Html()));
  }

  public function postContact() {
    // captcha instance of the contact page
    $captcha = $this->getContactCaptchaInstance();

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

      $validator  = Validator::make(Input::all(), array(
            'name' => 'required|min:5',
            'email' => 'required|email',
            'subject' => 'required|min:10',
            'message' => 'required|min:20',
        )
      );

      if (!$isHuman || $validator->fails()) 
      {
        if (!$isHuman)
          {
              $validator->errors()->add('CaptchaCode', 'Wrong code. Try again please.');
          }

          return Redirect::to('contact')
                    ->withInput()
                    ->withErrors($validator->errors());
      }

      // Captcha validation passed
      // TODO: send email

      return Redirect::to('contact')
                    ->with('status', 'Your message was sent successfully.');
  }

}

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 4.2 integration guide.

After creating a function to get an instance of the Captcha class called getContactCaptchaInstance(), the getContact() action refers contact view and pass a Captcha Html to View by pass an array of data as the second parameter to the view helper (or you can also use the with() method) method on HTTP GET request.

On HTTP POST request (which occurs when user submits the form), the postContact() action is executed and this is where we validate the user's Captcha code input (using the Validation class) and validate Captcha Code using the Validate() method of the $captcha object.

Finally, we redirect user to contact page and pass some data to contact view.

Captcha configuration options – /app/config/captcha_config/ContactCaptchaConfig.php

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

$LBD_CaptchaConfig = CaptchaConfiguration::GetSettings();

$LBD_CaptchaConfig->CodeLength = CaptchaRandomization::GetRandomCodeLength(4, 6);

In the code above, we have overridden the default settings of library. 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.