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

Laravel中CustomRequest验证失败时自定义message字段内容

当然可以!这在Laravel里非常容易实现

你只需要在你的CustomRequest类中重写response方法,就能完全自定义验证失败时返回的响应内容。具体步骤如下:

  1. 打开你的CustomRequest文件(一般在app/Http/Requests目录下)
  2. 添加下面的方法到类中:
/**
 * Get the response for a failed validation.
 *
 * @param  array<string, array<string>>  $errors
 * @return \Illuminate\Http\JsonResponse
 */
public function response(array $errors)
{
    return response()->json([
        'message' => 'custom message only for this CustomRequest fail.',
        'errors' => $errors
    ], 422);
}

这样当这个请求类的验证失败时,就会返回你想要的自定义message,同时保留原来的errors结构。

另外还有一种方式,如果你想通过抛出异常的方式来处理,可以重写failedValidation方法:

use Illuminate\Validation\ValidationException;

/**
 * Handle a failed validation attempt.
 *
 * @param  \Illuminate\Contracts\Validation\Validator  $validator
 * @return void
 *
 * @throws \Illuminate\Validation\ValidationException
 */
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    $exception = ValidationException::withMessages($validator->errors()->toArray());
    
    // 自定义响应内容
    $exception->response = response()->json([
        'message' => 'custom message only for this CustomRequest fail.',
        'errors' => $validator->errors()->toArray()
    ], 422);

    throw $exception;
}

两种方式都能达到你的需求,第一种重写response方法更简洁直接,推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:37:23