Search code examples
validationlaravel-4ardent

How to validate a form field but not store it in the database


I have a form with a checkbox field for users to accept terms and conditions. currently if validation passes all the fields will be stored in the database.

I tried to exclude this field by setting the input variable:

$input = Input::except('terms_and_conditions');

But this seems to be getting ignored because the form still validates and all fields get stored in the database.

Is it possible to include a field in validation but exclude it from being stored in the database?

The Form:

    {{ Form::open(['route' => 'questions.store', 'method' => 'POST']) }}
      {{ Form::text('firstname', '', ['placeholder' => 'First Name', 'class' => 'form-control']) }}
      {{ Form::text('lastname', '', ['placeholder' => 'Last Name', 'class' => 'form-control']) }}
      {{ Form::email('email', '', ['placeholder' => 'Email', 'class' => 'form-control']) }}
      {{ Form::textarea('question', '', ['placeholder' => 'Question', 'class' => 'form-control']) }}
      {{ Form::checkbox('terms_and_conditions', 1) }}
      {{ Form::label('terms_and_conditions', 'I agree to terms and conditions') }}<br/>
      <p class="text-center">{{ Form::button('', ['type' => 'submit', 'class' => 'iconic iconic-chevron-right LearnMoreChevron']) }}</p>
    {{ Form::close() }}

The Validation (In the model, using Ardent package):

 public static $rules = array(
  'firstname' => 'required|between:2,20',
  'lastname' => 'required|between:2,30',
  'email' => 'required|email',
  'question' => 'required|max: 5000',
  'terms_and_conditions' => 'Accepted'
 );

The Controller function:

public function store() {
  $input = Input::except(array('terms_and_conditions'));

  $question = Question::create( $input );

  if ($question->save()) {
  return Redirect::to('/#Questions')->with('message', 'Your question has been submitted.');
  } else {
  return Redirect::to('/#Questions')->withErrors( $question->errors() );
  }
}

Solution

  • I would say to exclude that field from the model since it doesn't belong to.

    if ( ! (bool) Input::get("terms_and_conditions") ) {
        return Redirect::to('/#Questions')->withErrors(array("You need to accept our terms and conditions"));
    }