Php 无法从Laravel表单请求验证中的对象数组中排除空值?
注意:将“详细信息”存储为数据库中的json字段 表单请求验证代码:Php 无法从Laravel表单请求验证中的对象数组中排除空值?,php,laravel,laravel-7,Php,Laravel,Laravel 7,注意:将“详细信息”存储为数据库中的json字段 表单请求验证代码: public function rules(Request $request) { return [ 'name' => 'required | string', 'details.subscriptions' => 'required | array', 'details.subscriptions.*' => 'nullable | string',
public function rules(Request $request)
{
return [
'name' => 'required | string',
'details.subscriptions' => 'required | array',
'details.subscriptions.*' => 'nullable | string',
'details.size' => 'nullable | array',
'details.size.*' => 'nullable | string',
'details.notes' => 'nullable | array',
'details.notes.*' => 'nullable | string',
'details.price' => 'nullable | array',
'details.price.*' => 'nullable | double',
];
}
protected function prepareForValidation()
{
$this->merge([
'name' => ucwords($this->name),
]);
}
验证结果-我得到的:
{
"name":"Some Name",
"details":{
"subscriptions":["1"],
"size":[null,null],
"notes":["10 pcs",null],
"price":[100,null]}
}
我想要的是:
{
"name":"Some Name",
"details":{
"subscriptions":["1"],
"notes":["10 pcs"],
"price":[100]
}
}
请帮忙,我卡住了
已在控制器存储方法中尝试此操作:
$validated = $request->validated();
$collection = collect($validated);
$size = array_filter($validated['details']['size'], function (
$value
) {
return !is_null($value);
});
这将返回一个空数组。但是我不知道下一步该怎么办。只要有
null
值,就可以进行筛选,如果数组现在为空,则可以再次筛选。实现这一点有多种方法,这只是一种可能的解决方案
<?php
$validated = json_decode('{
"name":"Some Name",
"details":{
"subscriptions":["1"],
"size":[null,null],
"notes":["10 pcs",null],
"price":[100,null]}
}', true);
//filter null values
foreach($validated['details'] as $key => $detail) {
$validated['details'][$key] = array_filter($validated['details'][$key], function ($value) {
return !is_null($value);
});
}
//filter empty arrays
$validated['details'] = array_filter($validated['details'], function ($value) {
return !empty($value);
});
print_r($validated);
您可以创建递归过滤器
public function index(YourRequest $request)
{
$validated = $request->validated();
$validated = $this->filterRecursive($validated);
dd($validated);
}
public function filterRecursive($values)
{
foreach ($values as &$value) {
if (is_array($value)) {
$value = $this->filterRecursive($value);
}
}
return array_filter($values);
}
您需要一个强制转换,以允许发送空值,但在验证后进行筛选?@Svetoslav我已经这样做了。@FelippeDuarte尝试使用筛选进行此操作,但未成功。你能帮忙吗?验证不是一个过滤器。您尝试过滤现有数据的代码在哪里?