我正在使用laravel 5.6,我需要过滤输入。 laravel有相当漂亮的验证系统。我想知道有什么方法可以消除那些不正确的结果,而不是在输入不符合规则时显示错误。像下面的例子 这是我的规则
$this->validate($request , [
'room_attributes.*.title' => 'required' ,
'room_attributes.*.value' => 'required' ,
]);
这些是我从表单中收到的数据
"room_attributes" => array:6 [▼
0 => array:2 [▼
"title" => "title 1"
"value" => "val1"
]
1 => array:2 [▼
"title" => "title2"
"value" => "val2"
]
2 => array:2 [▼
"title" => "title3"
"value" => null
]
3 => array:2 [▼
"title" => null
"value" => "val4"
]
4 => array:2 [▼
"title" => null
"value" => null
]
5 => array:2 [▼
"title" => null
"value" => null
]
]
根据当前规则,我会收到这些错误
The room_attributes.3.title field is required.
The room_attributes.4.title field is required.
The room_attributes.5.title field is required.
The room_attributes.2.value field is required.
The room_attributes.4.value field is required.
The room_attributes.5.value field is required.
但是我想过滤我的数据,所以我过滤我的输入并接收此数组作为结果(仅有两个同时填充了标题和值的数组)
0 => array:2 [▼
"title" => "title 1"
"value" => "val1"
]
1 => array:2 [▼
"title" => "title2"
"value" => "val2"
]
剂量laravel提供类似功能吗? laravel本身还是一些第三方库?
预先感谢
答案 0 :(得分:0)
您可以尝试这样的事情:
$data = $request->all();
$data['room_attributes'] = collect($data['room_attributes'])->filter(function($item){
return !is_null($item['title']) && !is_null($item['value']);
})->toArray();
Validator::make($data, [
'room_attributes.*.title' => 'required',
'room_attributes.*.value' => 'required',
])->validate();
有关过滤器收集方法的更多信息:https://laravel.com/docs/5.7/collections#method-filter