Laravel 4.2 Form Validation BotDetect CAPTCHA Example

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 BotDetect PHP Captcha validation and Laravel validation functionality. It uses Laravel's Forms & HTML and 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.

Config – /config/captcha.php

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

// BotDetect PHP Captcha configuration options

return array(
  // Captcha configuration for contact page
  'ContactCaptcha' => array(
    'UserInputID' => 'CaptchaCode',
    'CodeLength' => CaptchaRandomization::GetRandomCodeLength(4, 6),
    'ImageStyle' => ImageStyle::AncientMosaic,
  ),

);

In order to use the Laravel CAPTCHA Package, we have declared Captcha configuration which will be used when showing Captcha image in contact view. Detailed description of this approach is available in a BotDetect Laravel 4.2 integration guide.

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(captcha_layout_stylesheet_url()) }}

  <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 -->
        {{ captcha_image_html('ContactCaptcha') }}
      </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 above code uses captcha_image_html() helper function to generate Captcha image. It is required to pass a captcha configuration key defined in app/config/captcha.php file.

The View needs to add the required stylesheet of the library by calling captcha_layout_stylesheet_url() helper function.

Controller – /app/controllers/ContactController.php

<?php

class ContactController extends BaseController {

  public function getContact() {
    return View::make('contact');
  }

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

    if ($validator->fails()) 
    {
      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.

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 by using the valid_captcha validation rule.

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