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

Laravel 9 API中能否对数组内对象按类型应用不同表单验证规则?

Laravel 9 数组内字段的差异化验证解决方案

问题原因

你当前的验证规则无法生效,是因为request()->input('shapes.*.type')返回的是所有shape的type组成的数组(比如['Point', 'MultiPolygon']),用数组和字符串'Point'做相等判断结果永远为false,导致所有coordinates都应用了MultiPolygonCoordinatesValidator。

可行解决方案

方案一:遍历生成索引级验证规则

直接遍历请求中的shapes数组,为每个索引对应的coordinates字段单独设置验证规则:

public function rules()
{
    $baseRules = [
        'shapes' => 'required|array|min:1',
        'shapes.*.type' => [
            'required',
            'string',
            'in:Point,MultiPolygon',
        ],
    ];

    // 为每个shape的coordinates添加对应规则
    foreach ($this->input('shapes', []) as $index => $shape) {
        $baseRules["shapes.$index.coordinates"] = [
            'required',
            $shape['type'] === 'Point' 
                ? new PointCoordinatesValidator 
                : new MultiPolygonCoordinatesValidator,
        ];
    }

    return $baseRules;
}

方案二:通过withValidator动态添加规则

利用表单请求的withValidator方法,在验证器实例初始化后动态注入规则:

public function rules()
{
    return [
        'shapes' => 'required|array|min:1',
        'shapes.*.type' => [
            'required',
            'string',
            'in:Point,MultiPolygon',
        ],
    ];
}

public function withValidator($validator)
{
    foreach ($this->input('shapes', []) as $index => $shape) {
        $validator->addRules([
            "shapes.$index.coordinates" => [
                'required',
                $shape['type'] === 'Point' 
                    ? new PointCoordinatesValidator 
                    : new MultiPolygonCoordinatesValidator,
            ],
        ]);
    }
}

这两种方案都能准确根据每个shape的type值,为对应的coordinates字段应用正确的自定义验证器。

内容的提问来源于stack exchange,提问作者Hoult74

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:40:31