验证 Laravel 中的 JSON 数组

Validating a JSON array in Laravel

我有一个控制器接收以下 POST 请求:

{
  "_token": "csrf token omitted",
  "order": [1,2,3,4,5,6,7,8]
}

如何使用验证器来确保 order 中的元素是唯一的,并且在 1 到 7 之间?我尝试了以下方法:

$this->validate($request, [
    'order' => 'required|array',
    'order.*' => 'unique|integer|between:1,7'
]);

检查第一个子句,即使输入无效,第二个子句也会通过。

unique 验证器关键字用于检查数据库中值的重复项。

对于这种情况,您应该使用自定义验证器。

参见:https://laravel.com/docs/5.1/validation#custom-validation-rules

使用distinct rule:

distinct

When working with arrays, the field under validation must not have any duplicate values.

在你的情况下,它可能看起来像这样:

$this->validate($request, [
    'order' => 'required|array',
    'order.*' => 'distinct|integer|between:1,7'
]);