Laravel Form Request校验中如何过滤JSON字段内数组的null值?
问题背景
- 数据库存储
details字段时使用JSON格式 - 现有Form Request 校验规则定义如下:
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), ]); }
- 实际拿到的校验通过结果带冗余null值,结构如下:
{ "name": "Some Name", "details": { "subscriptions": ["1"], "size": [null, null], "notes": ["10 pcs", null], "price": [100, null] } }
- 期望的最终存储结构(完全剔除冗余null值、空数组字段):
{ "name": "Some Name", "details": { "subscriptions": ["1"], "notes": ["10 pcs"], "price": [100] } }
- 之前在控制器的store方法中尝试用
array_filter处理size字段,结果返回空数组,不清楚后续调整方向。
落地解决方法
不需要在控制器里零散写各个字段的过滤逻辑,直接在Form Request层完成数据清洗,从根源上避免冗余代码,两种可直接复用的实现:
方法1:借助Form Request内置的passedValidation钩子统一清洗
Laravel的Form Request在校验完全通过后会自动触发passedValidation方法,在这里修改完校验数据包后,后续调用$request->validated()拿到的就是清洗完成的结果,代码直接写在当前的Form Request类里即可:
/** * 校验完成后自动清洗冗余数据 */ protected function passedValidation() { $originalDetails = $this->validated()['details'] ?? []; $cleanedDetails = []; foreach ($originalDetails as $fieldKey => $fieldValue) { // 只处理数组类型的details子字段 if (!is_array($fieldValue)) continue; // 过滤掉数组里的null值,同时重置数组索引 $filteredValue = array_values( array_filter($fieldValue, fn($item) => !is_null($item)) ); // 过滤后数组不为空才保留这个字段,空数组直接剔除 if (!empty($filteredValue)) { $cleanedDetails[$fieldKey] = $filteredValue; } } // 用清洗后的数据覆盖原有请求中的details字段 $this->merge([ 'details' => $cleanedDetails ]); }
- 针对性解决之前的踩坑点:
之前你用array_filter处理size字段得到空数组是正常现象,因为原size字段本身的两个元素都是null,过滤完自然是空数组。只要再加一层判断:过滤后是空数组的字段就从details里删除,就能完全匹配你期望的输出结构,不需要额外处理。
方法2:如果不想修改Form Request,在控制器层做统一递归清洗
如果不想动Form Request的逻辑,把之前零散的单字段过滤改成统一递归清洗即可:
// 拿到校验通过的原始数据 $validated = $request->validated(); // 递归清洗:剔除所有数组内的null值,移除空数组字段 $cleaned = json_decode(json_encode($validated), true); array_walk_recursive($cleaned, function(&$value) { if (is_array($value)) { $value = array_values(array_filter($value, fn($item) => !is_null($item))); } }); // 移除所有值为空数组的顶层key $cleaned['details'] = array_filter($cleaned['details'] ?? [], fn($item) => !empty($item));
- 常见注意事项:
使用array_filter时一定要显式指定回调只剔除null值,不要直接不传参数调用。默认的array_filter会把空字符串、数值0、布尔值false这些合法的业务值也过滤掉,很容易把价格为0的正常数据误删。
过滤完数组一定要用array_values重置索引,不然数组会保留原来的键位断层,转成JSON后变成对象格式,不符合预期的数组结构。
内容的提问来源于stack exchange,提问作者learner
相关产品推荐
相关产品推荐

