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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46670018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:46:56  来源:igfitidea点击:

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

laravellaravel-5laravel-5.5laravel-requestlaravel-response

提问by eithed

I'm trying to use Laravel validation to generate custom error message, however I'm unable to find the function I should be overriding.

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

Route: POST:/entries/uses EntryController@storewhich uses EntryStoreRequestto perform validation.

Route:POST:/entries/使用EntryController@storewhich用于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;
    }
}

The errors are currently returned as:

错误当前返回为:

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

I want to format them as:

我想将它们格式化为:

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

How can I achieve this within the ApiRequestclass?

我怎样才能在ApiRequest课堂上做到这一点?

回答by Marcin Nabia?ek

If you want to customize validation response only for selected Request class, you need to add failedValidation()message to this 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);
}

This way you don't need to change anything in Handler and have this custom response only for this single class.

通过这种方式,您无需在 Handler 中更改任何内容,并且仅为该单个类提供此自定义响应。

And if you want to change format globally for all responses you should add to app\Exceptions\Handler.phpfile the following method:

如果您想全局更改所有响应的格式,您应该将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);
}

You can read about this also in Upgrade guidein Exception Formatsection

您也可以在异常格式部分的升级指南中阅读有关此内容的信息