'required_if' 在数据库检查的同时进行验证 Laravel 5

'required_if' validation alongside database check in Laravel 5

我正在实施一个调查生成器,其中包含多个允许的问题类型。这些类型是:

  1. 单选
  2. 多选
  3. 星级

1.2. 需要多个可能的答案用户,而 3. 根本不需要任何可能的答案。这些要求在 question_types.multiple_answers 列中存储为 true / false 值。

我需要一个验证规则,它将:

require answers[] array to be present in the request, only if the selected question_type's corresponding multiple_answers 在数据库中设置为 true


下面是我要实现的目标的说明:

...->validate($request, [
    'answers' => 'require_if:type,...' // <-- if 'type' has 'multiple_answers' set to true in database
]);

你可以创建 conditional validation rules 来做你想做的事。仅当指定为第三个参数的函数 returns true.

时,才会评估指定为第二个参数的规则
$v->sometimes('answers', 'required', function($input) {
    // check database and return true if multiple_answers is set for the type ($input->type)
});