laravel 5.6过滤表单中输入的数据



我使用的是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提供这样的功能吗?要么是拉拉威尔自己,要么是某个第三方图书馆?

提前感谢

你可以试试这样的东西:

$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-过滤

最新更新