首页 > 解决方案 > 如何使用请求验证 Laravel 中的数组?

问题描述

我发送到Laravel这个JSON数据:

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

我有一个 StoreRequest 类扩展FormRequest

<?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;
    }

我在请求规则()中找到了处理数组的解决方案:

    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()

标签: phplaravellaravel-5.8request-validation

解决方案


由于您有一组数据,因此您需要先放置*

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

推荐阅读