【问题标题】:'required_if' validation alongside database check in Laravel 5'required_if' 验证以及 Laravel 5 中的数据库检查
【发布时间】:2016-12-09 13:21:33
【问题描述】:

我正在实施一个带有几种允许的问题类型的调查生成器。这些类型是:

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

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

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

要求answers[]数组出现在请求中,仅当选定的question_type's对应的multiple_answers在数据库


这是我想要达到的目标的说明:

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

【问题讨论】:

  • stackoverflow.com/questions/37935804/… 这可能对你有帮助..
  • @Avishek 谢谢你,但情况不同。我需要检查数据库中的条件并要求基于该条件的字段
  • 这意味着您要在数据库的not null 列的基础上添加required fields..?
  • 是的,我想要一个验证来检查数据库中的现有条目并据此做出决定
  • 为什么不在控制器中创建动态规则:$rules = []; if(multi_answers){ $rules = [ 'answers' =&gt; 'required'] } else {//other thing}

标签: php laravel laravel-5 laravel-validation


【解决方案1】:

您可以创建conditional validation rules 来做您想做的事。只有当指定为第三个参数的函数返回 true 时,才会评估指定为第二个参数的规则。

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

【讨论】:

    猜你喜欢
    • 2016-10-13
    • 2021-03-06
    • 2019-03-21
    • 2022-12-08
    • 1970-01-01
    • 2015-05-24
    • 1970-01-01
    • 2018-08-27
    • 2019-12-16
    相关资源
    最近更新 更多