You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中使用FormRequest按对象类型验证动态参数对象数组

校验方案说明

完全可以通过 FormRequest 实现按数组内对象的type字段动态校验的需求,具体实现步骤如下:

1. 基础规则定义

先在 FormRequest 的rules方法中定义通用校验规则,先保证外层数组结构、每个对象的type字段合法:

public function rules()
{
    return [
        // 若请求直接提交目标数组,不需要外层字段,规则改为 '*' => 'required|array'
        'list' => 'required|array',
        'list.*.type' => 'required|in:link,image',
    ];
}

2. 动态规则扩展(核心实现)

重写 FormRequest 的withValidator方法,通过后置校验钩子根据每个对象的type值匹配对应的校验规则:

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        // 若直接提交数组,这里改为 $this->all()
        $itemList = $this->input('list', []);
        
        foreach ($itemList as $index => $item) {
            $ruleMap = match($item['type']) {
                'link' => [
                    'url' => 'required|url'
                ],
                'image' => [
                    'id' => 'required|string',
                    'image' => 'required|url'
                ],
                default => []
            };

            // 逐字段校验当前下标的对象
            foreach ($ruleMap as $field => $rule) {
                $fieldPath = "list.{$index}.{$field}";
                // 若直接提交数组,字段路径改为 "{$index}.{$field}"
                $fieldValidator = \Validator::make($this->input(), [$fieldPath => $rule]);
                if ($fieldValidator->fails()) {
                    foreach ($fieldValidator->errors()->all() as $error) {
                        $validator->errors()->add($fieldPath, $error);
                    }
                }
            }
        }
    });
}

若使用 Laravel 8 以下版本不支持match表达式,可替换为switch语句或数组映射实现规则匹配。

3. 自定义错误提示(可选)

可在messages方法中自定义更友好的错误提示,支持使用:position占位符标记数组下标:

public function messages()
{
    return [
        'list.*.type.in' => '第:position个元素的类型仅支持link、image',
        'list.*.url.required' => '第:position个link类型元素的url为必填项',
        'list.*.id.required' => '第:position个image类型元素的id为必填项',
    ];
}

内容的提问来源于stack exchange,提问作者Alexander K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 18:39:03