我想知道是否可以在 Laravel 中验证一组对象?我使用 vue 构建了一个看起来像 Excel 页面的表单,因此用户可以编辑稍后上传的许多行。
我希望在发布到我的控制器时验证的数据如下所示:
rows[
0 {
title: "my title",
post: "my post text"
},
1 {
title: "my title",
post: "my post text"
},
2 {
title: "my title",
post: "my post text"
}
]
Run Code Online (Sandbox Code Playgroud)
例如,如何向每个输入添加所需的规则?
小智 22
您可以使用 Laravel 的数组验证。
例如。
$validator = Validator::make($request->all(), [
'row.*.title' => 'required',
'row.*.post' => 'required',
]);
Run Code Online (Sandbox Code Playgroud)
您可以在此处找到有关 Laravel 数组验证的更多信息
Mic*_*son 13
如果您发布一个数组,则批准的答案有效,但是为了更进一步,我需要保存多个数组。虽然如果我创建两个单独的端点,这种方法就可行,但如果我想将所有内容保存在一个端点中怎么办DB::transaction?
中提琴:
// POST:
{
"array1": [
{ "key1": "string", "key2": 1 },
{ "key1": "string", "key2": 0 }
],
"array2": [
{ "key3": "string", "key4": 1 },
{ "key3": "string", "key4": 0 }
]
}
Run Code Online (Sandbox Code Playgroud)
// SERVER:
$this->validate($request, [
'array1' => 'present|array',
'array2' => 'present|array',
'array1.*.key1' => 'required|string',
'array1.*.key2' => 'required|integer',
'array2.*.key3' => 'required|string',
'array2.*.key4' => 'required|integer'
]);
DB::transaction(function() use($request) {
foreach($request['array1'] as $x){
// ...do stuff here
};
});
Run Code Online (Sandbox Code Playgroud)
注意:'present|array'接受空数组而'required|array'拒绝它们。
| 归档时间: |
|
| 查看次数: |
14086 次 |
| 最近记录: |