如何验证表单字段但不将其存储在数据库中

时间:2014-07-10 15:44:29

标签: validation laravel-4 ardent

我有一个带有复选框字段的表单,供用户接受条款和条件。目前,如果验证通过,则所有字段都将存储在数据库中。

我尝试通过设置输入变量来排除此字段:

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

但是这似乎被忽略了,因为表单仍然有效并且所有字段都存储在数据库中。

是否可以在验证中包含一个字段,但将其排除在存储在数据库中?

表格:

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

验证(在模型中,使用Ardent包):

 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'
 );

控制器功能:

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

1 个答案:

答案 0 :(得分:0)

我想说从模型中排除该字段,因为它不属于。

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