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_iderror messages to referenceimage_pathinstead of the original field name. - Collects all validation errors under the
image_pathkey. - 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
相关产品推荐
相关产品推荐

