Laravel自定义验证规则:如何访问数组表单字段对应属性值
Laravel 自定义验证规则中访问数组表单对应字段的解决方案
问题背景
在Laravel中创建自定义验证规则时,需要访问数组表单里对应索引的字段值。表单包含多个以resource[{?}]命名的下拉框,分别为designation和allocation。控制器为resource.*.allocation字段应用了自定义规则ResourceQuotation,但在规则的passes方法中无法正确获取对应索引的designation值,同时不清楚如何处理多数组项的验证,以及如何为每个项显示单独的错误提示。
用户提供的代码
HTML 代码
<!-- Designation Dropdown --> <select name="resource[{?}][designation]"> <option value=1>First Value</option> <option value=2>Second Value</option> </select> <!-- Allocation Dropdown --> <select name="resource[{?}][allocation]"> <option value=1>First Value</option> <option value=2>Second Value</option> </select>
控制器验证规则代码
'resource.*.allocation' => ['required', new ResourceQuotation()], 'resource.*.designation' => 'required',
自定义验证规则ResourceQuotation代码
public function passes($attribute, $value) { // 困惑:如何获取对应索引的designation值,因为可能有多个项 $designation = request()->input("resource.*.designation"); $allocations = ResourcePrice::select('allocation','fixed_allocation') ->where('id',$designation) ->first(); if($allocations->fixed_allocation=1){ $this->message = "Maximum allocation allowed is 10%"; return false; } else{ return true; } } public function message() { return $this->message; }
解决方案
1. 获取对应索引的designation值
passes方法中的$attribute参数是当前验证的完整字段名(比如resource[0].allocation),可以通过正则解析提取出数组索引,再获取对应位置的designation值:
public function passes($attribute, $value) { // 解析字段名,提取数组索引 preg_match('/resource\[(\d+)\]\.allocation/', $attribute, $matches); $index = $matches[1]; // 获取对应索引的designation值 $designation = request()->input("resource.$index.designation"); // 先判断designation是否存在,避免空值报错 if (!$designation) { $this->message = "请选择职位类型"; return false; } $allocations = ResourcePrice::select('allocation','fixed_allocation') ->where('id', $designation) ->first(); // 检查查询结果是否有效 if (!$allocations) { $this->message = "所选职位类型不存在"; return false; } // 注意用==做比较,避免赋值操作= if($allocations->fixed_allocation == 1){ $this->message = "最大分配比例为10%"; return false; } else{ return true; } }
2. 处理多数组项的验证
Laravel的resource.*.allocation规则会自动遍历所有数组项,为每个allocation字段单独调用ResourceQuotation规则的passes方法,无需额外编写遍历逻辑,只要保证每个项能正确获取对应索引的designation即可。
3. 为每个项显示单独的错误提示
Laravel会自动为每个数组字段生成带索引的错误键(比如resource.0.allocation),前端可以通过以下方式精准显示对应项的错误:
<!-- 遍历所有resource项的allocation错误 --> @foreach($errors->get('resource.*.allocation') as $error) <span class="text-danger">{{ $error[0] }}</span> @endforeach <!-- 针对单个索引项显示错误 --> @error('resource.0.allocation') <span class="text-danger">{{ $message }}</span> @enderror
如果需要在错误信息中明确标注是第几项,可以在passes方法中动态生成消息:
$this->message = "第".($index+1)."项:最大分配比例为10%";
内容的提问来源于stack exchange,提问作者Zack
相关产品推荐
相关产品推荐

