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

Laravel 8中如何自定义Request验证返回的错误提示消息

解决Laravel 8自定义表单请求验证顶层错误消息的方案

你可以根据实际需求选择全局修改或者仅针对特定请求修改两种实现方式:


方案1:全局修改接口验证错误返回规则(所有接口生效)

Laravel的JSON验证错误默认由app/Exceptions/Handler.php中的invalidJson方法处理,直接重写该方法即可统一修改顶层message的取值逻辑:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Throwable;

class Handler extends ExceptionHandler
{
    // 其他原有代码保持不变

    /**
     * 重写JSON验证错误的返回格式
     */
    protected function invalidJson($request, ValidationException $exception)
    {
        // 提取所有错误中的第一条提示作为顶层message
        $firstErrorMessage = collect($exception->errors())->flatten()->first();
        
        return response()->json([
            'message' => $firstErrorMessage ?: $exception->getMessage(),
            'errors' => $exception->errors()
        ], $exception->status);
    }
}

方案2:仅针对特定自定义Request生效(部分接口修改)

如果只需要当前提交的这个验证类生效修改,不需要全局改动,可以在你的自定义Request类中重写failedValidation方法:

<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use App\Models\User; // 确保引入你的User模型

class YourCustomRequest extends FormRequest
{
    public function rules()
    {
        // 你原有的rules逻辑保持不变
        return [
            'profile_img' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:' . config('filesystems.max_upload_size'),
            'name' => 'nullable|min:3',
            'phone' => [
                'required',
                'numeric',
                new UpdatePhoneRule(User::TYPE_CLIENT),
            ],
            'email' => [
                'nullable',
                'email',
                new UpdateEmailRule(User::TYPE_CLIENT),
            ]
        ];
    }

    /**
     * 验证失败时的自定义处理
     */
    protected function failedValidation(Validator $validator)
    {
        $errors = $validator->errors();
        // 取第一条错误作为顶层message
        $firstError = collect($errors)->flatten()->first();

        throw new HttpResponseException(response()->json([
            'message' => $firstError,
            'errors' => $errors
        ], 422));
    }
}

两种方案都可以实现手机号占用时,顶层message直接返回The phone has already been taken的效果,邮箱等其他字段的验证错误也会自动取第一条提示作为顶层消息。

内容的提问来源于stack exchange,提问作者Duy Nguyen Tho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:09:03