简体   繁体   English

Laravel 5中的'required_if'验证以及数据库检查

[英]'required_if' validation alongside database check in Laravel 5

I am implementing a survey builder with several allowed question types . 我正在实现一个带有几种允许的问题类型调查构建器 These types are: 这些类型是:

  1. Single choice 单选
  2. Multiple choice 多项选择
  3. Star rating 星级

The 1. and 2. require multiple possible answers to be given by a user, whereas the 3. does not require any possible answers at all . 1.2.要求用户给出多个可能的答案 ,而3. 根本不需要任何可能的答案 These requirements are stored as true / false values in question_types.multiple_answers column. 这些要求被存储为true / false价值观question_types.multiple_answers列。

I need a validation rule, that will: 我需要一个验证规则,它将:

require answers[] array to be present in the request, only if the selected question_type's corresponding multiple_answers value is set to true in the database . 需要 answers[]阵列存在于该请求, 仅当所选question_type's对应multiple_answers设置为true在数据库中


Here is an illustration of what I'm trying to achieve: 这是我要实现的目标的说明:

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

You can create conditional validation rules to do what you want. 您可以创建条件验证规则以执行所需的操作。 The rule specified as the second parameter will only be evaluated if the function specified as the third parameter returns true. 仅当指定为第三个参数的函数返回true时,才会评估指定为第二个参数的规则。

$v->sometimes('answers', 'required', function($input) {
    // check database and return true if multiple_answers is set for the type ($input->type)
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM