【问题标题】:laravel 5.4 validate array with custom rulelaravel 5.4 使用自定义规则验证数组
【发布时间】:2018-04-24 17:50:23
【问题描述】:

我在验证需要自定义规则的字段数组时遇到问题。我有以下验证器:

$validator = Validator::make($request->all(), [
     'order'        => 'required',
     'service_id.*' => Rule::unique('order_services')->where('order_id', $request->order),
     'due_date.*'   => 'required|date',
     'vendor'   => 'required|integer',
     'instructions' => 'string|nullable',
     'lock_box' => 'string|nullable',
  ]);

到期日期数组验证正常,但服务 id 返回以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'service_id.0' in 'where clause' (SQL: select count(*) as aggregate from `order_services` where `service_id`.`0` = 10 and `order_id` = 100f)

服务id规则防止相同订单号和服务id的重复记录

验证单个服务 ID 时,该规则按预期工作,我只是不确定如何同时验证多个服务 ID。

提前致谢

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.4 laravel-validation


    【解决方案1】:

    默认情况下,Laravel 使用unique 角色的键,因为它是一个数组,所以键是 0、1、2 等等。解决方案是为唯一规则添加列名,如下所示:

    Rule::unique('order_services', 'id')->where('order_id', $request->order),
    

    显然,在您的情况下,您可能需要 id 以外的其他列名(这取决于您的应用程序)

    【讨论】:

    • 谢谢!我最终使用了 Rule::unique('order_services', 'service_id')->where('order_id', $request->order),
    猜你喜欢
    • 2018-10-25
    • 2017-04-11
    • 2018-02-18
    • 2014-04-22
    • 2019-02-12
    • 2016-11-22
    • 2017-12-01
    • 2018-01-12
    • 2017-12-06
    相关资源
    最近更新 更多