使用 Laravel,有没有办法在一个 ajax 调用中对多个模型的数据进行 运行 验证?

Using Laravel, is there a way to run validation on one ajax call with data for multiple models?

假设一个人当时通过JSONpost一个模型的多个数据集,可以使用Eloquent的Model::create( ) 功能。但是,就我而言,我还需要验证此数据。

Validator 仅将 Request 对象作为输入,据我所知,我无法仅使用一个模型创建新的 Request 实例。

假设这将是输入数据 (JSON),索引是浏览器知道哪些数据属于哪些项目的值(因为它们在创建时没有分配唯一 ID )

[
    {
        "index" : 1,
        "name"  : "Item 1",
        "value" : "Some description"
    },
    {
        "index" : 2,
        "name"  : "Item 2",
        "value" : "Something to describe item 2"
    },
    (and so on)
]

根数组中的每个对象都需要运行通过同一个验证器。它的规则在 Model::$rules (public static array) 中定义。

是否有办法 运行 针对每个项目的验证器,并可能捕获每个项目的错误?

您可以利用 Validator 进行手动验证:

...
use Validator;
...
$validator = Validator::make(
    json_decode($data, true), // where $data contains your JSON data string
    [
        // List your rules here using wildcard syntax.
        '*.index' => 'required|integer',
        '*.name' => 'required|min:2',
        ...
    ],
    [
        // Array of messages for validation errors.
        ...
    ],
    [
        // Array of attribute titles for validation errors.
        ...
    ]
);

if ($validator->fails()) {
    // Validation failed.
    // $validator->errors() will return MessageBag with what went wrong.    
    ...
}

您可以阅读有关验证数组的更多信息 here