是否可以从输入数组(或至少索引)中获取失败的元素?
示例:
$data = [
['name' => 'John', 'age' => 30],
['name' => 'Robert', 'age' => 'nope'],
['name' => ['woops'], 'age' => 10]
];
$validator = \Validator::make($data, [
'*.name' => 'required|string|max:200',
'*.age' => 'required|int'
]);
if(!$validator->passes()){
/*
Get all the failed elements.
In this case:
[
['name' => 'Robert', 'age' => 'nope'],
['name' => ['woops'], 'age' => 10]
]
*/
$fails = $validator->getFailElements();
// OR
/*
Get failed indexes:
[1,2]
*/
$indexes = $validator->getFailIndexes();
//Proceed...
}
原因是我想在表格中插入无效数据,因此可以稍后修复这些条目......
答案 0 :(得分:2)
您可以在验证程序上调用invalid()
以获取失败的数据。
$failed = $validator->invalid();
参考:https://github.com/illuminate/validation/blob/master/Validator.php#L544
答案 1 :(得分:0)
试试这个
$validator = \Validator::make($data, [
'*.name' => 'required|string|max:200',
'*.age' => 'required|int'
]);
if ($validator->fails()) {
dd($request->all());
//do your code
}