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

如何添加或自定义Laravel验证的响应格式

Laravel自定义验证响应格式:添加status字段并设为FAILED

问题场景

当前Laravel验证失败时返回的响应格式如下:

{
    "message": "The expected salary field is required.",
    "errors": {
        "expected_salary": [
            "The expected salary field is required."
        ]
    }
}

需要调整为包含status字段的格式,期望输出:

{
    "status": "FAILED",
    "message": "The expected salary field is required.",
    "errors": {
        "expected_salary": [
            "The expected salary field is required."
        ]
    }
}

当前使用的验证规则:

public function rules()
{
    return ['expected_salary' => 'required'];
}

解决方案

以下是几种实现自定义验证响应格式的常用方式,按需选择:

1. 自定义表单请求类中重写failedValidation

如果项目使用**表单请求(Form Request)**做验证,直接在对应请求类中重写该方法,针对性修改响应:

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Foundation\Http\FormRequest;

class SalaryRequest extends FormRequest
{
    public function rules()
    {
        return [
            'expected_salary' => 'required'
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(
            response()->json([
                'status' => 'FAILED',
                'message' => $validator->errors()->first(),
                'errors' => $validator->errors()->toArray()
            ], 422)
        );
    }
}

2. 全局统一处理验证异常

如果需要所有接口的验证失败响应都统一格式,修改异常处理器:
在app/Exceptions/Handler.php(Laravel 8+版本)中添加以下逻辑:

use Illuminate\Validation\ValidationException;

public function register()
{
    $this->renderable(function (ValidationException $e, $request) {
        // 仅针对JSON请求生效
        if ($request->expectsJson()) {
            return response()->json([
                'status' => 'FAILED',
                'message' => $e->validator->errors()->first(),
                'errors' => $e->validator->errors()->toArray()
            ], $e->status);
        }
    });
}

3. 控制器内手动验证时自定义响应

如果是在控制器中手动调用验证,直接在失败分支返回自定义响应:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

public function submitSalary(Request $request)
{
    $validator = Validator::make($request->all(), [
        'expected_salary' => 'required'
    ]);

    if ($validator->fails()) {
        return response()->json([
            'status' => 'FAILED',
            'message' => $validator->errors()->first(),
            'errors' => $validator->errors()->toArray()
        ], 422);
    }

    // 业务逻辑处理...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:36:34