Laravel动态添加的otherStudies表单字段未传入request()->validate()问题
问题原因及解决方法
核心原因:表单字段命名格式不符合PHP解析规范
你当前的其他学习经历输入字段的name属性写法为otherStudies[0]other_studies_name,缺少数组层级之间的点分隔符。PHP解析表单提交的二维数组时,要求用.分隔数组索引和下一级键名,正确写法应为otherStudies[0].other_studies_name。
由于命名格式错误,这些字段不会被归到otherStudies数组下,只会被识别为独立的字符串键名。而你的校验规则匹配的是otherStudies.*前缀的数组字段,自然无法匹配到格式错误的键名,相关字段就会被校验逻辑过滤,不会出现在$validatedEducExp数组里。old()助手可以直接读取提交的原始键值,所以即使键名格式错误也能正常回显数据。
其他需要修复的问题
- 校验规则缺少nullable标记
当前otherStudies相关字段的校验规则没有添加nullable,如果用户对应字段留空,会触发校验规则拦截,导致字段被过滤。 - HTML标签闭合错误
代码中<td><textarea name="otherStudies[0]other_studies_awards" rows="3" cols="30"></textarea></td</tr>部分,</td缺少闭合的>,会导致浏览器解析DOM结构异常,极端情况下会让这部分输入框不属于<form>标签内部,导致提交数据异常。
修复步骤
- 修正所有otherStudies相关输入字段的
name属性,添加点分隔符,示例:
<input type="text" name="otherStudies[0].other_studies_name"/> <input type="text" name="otherStudies[0].other_studies_degree_major" placeholder="Masters Degree, Doctorate, Associate$quos, etc." /> <input type="text" style="width: auto; margin-top: 2rem;" name="otherStudies[0].other_studies_year"/> <input type="text" style="width: auto;" name="otherStudies[0].other_studies_units" cols="10"/> <textarea name="otherStudies[0].other_studies_awards" rows="3" cols="30"></textarea>
- 给otherStudies相关校验规则添加
nullable标记:
'otherStudies.*.other_studies_name' => ['nullable', 'max:100',new LetterSpaceOnly], 'otherStudies.*.other_studies_degree_major' => ['nullable', 'alpha','min:4','max:100'], 'otherStudies.*.other_studies_year' => ['nullable', new fromToYearRule], 'otherStudies.*.other_studies_units' => ['nullable', 'digits_between:1,2'], 'otherStudies.*.other_studies_awards' => ['nullable', 'string'],
- 修复HTML中闭合错误的
</td标签为</td>,保证DOM结构正常。 - 验证:修改完成后先在控制器执行
dd(request()->all()),确认原始请求中已经生成结构正确的otherStudies数组,再检查校验后的返回结果即可。
内容的提问来源于stack exchange,提问作者ellajhonm
相关产品推荐
相关产品推荐

