如何在Laravel 5.5中为选定的Request类设置自定义响应

eit*_*hed 6 laravel laravel-5 laravel-request laravel-response laravel-5.5

我正在尝试使用Laravel验证来生成自定义错误消息,但是我无法找到我应该重写的函数.

Route: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'
            ]
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

错误当前返回为:

{
    "message": "The given data was invalid.",
    "errors": {
        "message": [
            "The message field is required."
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

我想将它们格式化为:

{
    "data": [],
    "meta: {
        "message": "The given data was invalid.",
        "errors": {
            "message": [
                "The message field is required."
            ]
        }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能在ApiRequest课堂上实现这一目标?

Mar*_*łek 16

如果要仅为选定的Request类自定义验证响应,则需要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);
}
Run Code Online (Sandbox Code Playgroud)

这样您就不需要在Handler中更改任何内容,只对此单个类具有此自定义响应.

如果要为所有响应全局更改格式,则应将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);
}
Run Code Online (Sandbox Code Playgroud)

您也可以在" 异常格式"部分的" 升级指南"中了解此信息