laravel 如何验证json对象中的JSON对象数组?

2hh7jdfx  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(225)

我发送了一个JSON对象数组,并将其与其他数据一起发布到DB:

{
   "emotions":[
      {
         "id":1,
         "intensity":67,
         "new_intensity":67
      },
      {
         "id":2,
         "intensity":67,
         "new_intensity":67
      },
      {
         "id":3,
         "intensity":64,
         "new_intensity":64
      },
      {
         "id":4,
         "intensity":64,
         "new_intensity":64
      },
      {
         "id":5,
         "intensity":64,
         "new_intensity":64
      }
   ],
   "situation":"An event",
   
}

我想做的是验证situationemotions[{},{}] json数组:

控制器

public function store(Request $request)
{
   $this->validate($request, [
      'situation' => 'required',
   ]); 
   $data = ['data' => $request->input('emotions')];
   $this->validate($data, [
      'data.*.id' => 'digits:2|between:1,70',
      'data.*.intensity' => 'digits:3|between:1,100',
      'data.*.new_intensity' => 'digits:3|between:1,100'
   ]);
}

错误

传递给App\Http\Controllers\Controller::validate()的参数1必须是Illuminate\Http\Request的示例,给定数组
我希望能够合并这两种验证方法,但我不知道如何做到这一点?
Here is the answer I got my first try from

8mmmxcuj

8mmmxcuj1#

你可以使用数组验证器。下面的代码可以帮助你实现这一点

$validator = Validator::make($data, [
      'data.*.id' => 'digits:2|between:1,70',
      'data.*.intensity' => 'digits:3|between:1,100',
      'data.*.new_intensity' => 'digits:3|between:1,100'
   ])

您可以检查它是否失败并执行所需的操作

if($validator->fails()){
    // Do something
}
5hcedyr0

5hcedyr02#

它不应该工作。因为数组是数组的JSON对象。
我也面临着类似的问题。

相关问题