如何为 Laravel 5.5 中的选定请求 class 设置自定义响应

How to set custom response for selected Request class in Laravel 5.5

我正在尝试使用 Laravel 验证来生成自定义错误消息,但是我找不到我应该覆盖的函数。

路由:POST:/entries/ 使用 EntryController@store,后者使用 EntryStoreRequest 执行验证。

EntryStoreRequest

namespace App\Api\V1\Requests;

class EntryStoreRequest extends ApiRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'message' => [
                'string',
                'required',
                'max:65535',
            ],
            'code' => [
                'string',
                'max:255',
                'nullable'
            ],
            'file' => [
                'string',
                'max:255',
                'nullable'
            ],
            'line' => [
                'string',
                'max:255',
                'nullable'
            ],
            'stack' => [
                'string',
                'max:65535',
                'nullable'
            ]
        ];
    }
}

ApiRequest

namespace App\Api\V1\Requests;

use Illuminate\Foundation\Http\FormRequest;

abstract class ApiRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}

错误当前返回为:

{
    "message": "The given data was invalid.",
    "errors": {
        "message": [
            "The message field is required."
        ]
    }
}

我想将它们格式化为:

{
    "data": [],
    "meta: {
        "message": "The given data was invalid.",
        "errors": {
            "message": [
                "The message field is required."
            ]
        }
}

如何在 ApiRequest class 内实现此目标?

如果您只想为选定的请求 class 自定义验证响应,您需要向此 class 添加 failedValidation() 消息:

protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
    $response = new JsonResponse(['data' => [], 
             'meta' => [
                'message' => 'The given data is invalid', 
                'errors' => $validator->errors()
             ]], 422);

    throw new \Illuminate\Validation\ValidationException($validator, $response);
}

这样您就不需要在 Handler 中进行任何更改,并且仅针对单个 class.

使用此自定义响应

如果您想全局更改所有回复的格式,您应该将以下方法添加到 app\Exceptions\Handler.php 文件:

protected function invalidJson($request, ValidationException $exception)
{
    return response()->json([
             'data' => [], 
             'meta' => [
                'message' => 'The given data is invalid', 
                'errors' => $exception->errors()
             ]
             ], $exception->status);
}

您也可以在 Upgrade guide 异常格式 部分

中阅读相关内容

对于那些不想使用 JsonResponse 的人,这是我为自己所做的

protected function failedValidation(Validator $validator) {
        // if you want, log something here with $this->validationData(), $validator->errors()
        
        $response = redirect($this->getRedirectUrl())
            ->with('var1', 'my var 1') // custom flash variable to send if needed
            ->with('var2', 'my var 2')
            ->withErrors($validator)
            ->withInput();
        
        throw new ValidationException($validator, $response);
    }