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

Laravel验证:用单个字段统一返回一组关联字段的错误信息

Solution

In your FormRequest class, override the formatErrors method to re-map all validation errors from image_id and image_path into a single error entry under the image_path key. Here's how to implement it:

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Support\MessageBag;

class YourFormRequest extends \Illuminate\Foundation\Http\FormRequest
{
    public function rules()
    {
        return [
            'image_id' => ['required', 'integer'],
            'image_path' => ['required', 'url', 'min:2', 'max:500'],
        ];
    }

    protected function formatErrors(Validator $validator)
    {
        $errors = $validator->errors();
        $newErrors = new MessageBag();

        // Collect and re-map image_id errors to image_path key
        if ($errors->has('image_id')) {
            foreach ($errors->get('image_id') as $message) {
                // Replace 'image_id' with 'image_path' in the error message
                $adjustedMessage = str_replace('image_id', 'image_path', $message);
                $newErrors->add('image_path', $adjustedMessage);
            }
        }

        // Add existing image_path errors
        if ($errors->has('image_path')) {
            foreach ($errors->get('image_path') as $message) {
                $newErrors->add('image_path', $message);
            }
        }

        // Keep only the first error message as required
        if ($newErrors->count() > 1) {
            $firstMessage = $newErrors->first('image_path');
            $newErrors->forget('image_path');
            $newErrors->add('image_path', $firstMessage);
        }

        return $newErrors;
    }
}

How this works:

  • Retains your original validation rules to ensure both fields are validated correctly.
  • Rewords image_id error messages to reference image_path instead of the original field name.
  • Collects all validation errors under the image_path key.
  • Truncates multiple errors to a single entry to meet your requirement of returning one error message.

If you prefer a generic error message regardless of the specific validation failure, replace the message collection logic with this simplified version:

if ($errors->any()) {
    $newErrors->add('image_path', 'image_path is not set correctly');
}

内容的提问来源于stack exchange,提问作者Mr. Kenneth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:55:23