如何使用请求验证Laravel中的数组?

时间:2019-08-27 12:07:53

标签: php laravel laravel-5.8 request-validation

我将Laravel的数据发送到JSON

[
  {"name":"...", "description": "..."},
  {"name":"...", "description": "..."}
]

我有一个扩展了FormRequest的StoreRequest类:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|string|min:1|max:255',
            'description' => 'nullable|string|max:65535'
        ];
    }
}

在我的控制器中,我有以下代码,但不适用于数组:

    public function import(StoreRequest $request) {
        $item = MyModel::create($request);

        return Response::HTTP_OK;
    }

我发现这种解决方案可以处理Request rules()中的数组:

    public function rules()
    {
        return [
            'name' => 'required|string|min:1|max:255',
            'name.*' => 'required|string|min:1|max:255',
            'description' => 'nullable|string|max:65535'
            'description.*' => 'nullable|string|max:65535'
        ];
    }

如何更新StoreRequest和/或import()代码以避免在rules()中重复行?

1 个答案:

答案 0 :(得分:1)

如果您有一系列数据,则需要将*首先放在

public function rules()
{
   return [
       '*.name' => 'required|string|min:1|max:255',
       '*.description' => 'nullable|string|max:65535',
   ];
}