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

时间:2017-10-10 15:03:03

标签: laravel laravel-5 laravel-5.5 laravel-request laravel-response

我尝试使用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课程中实现这一目标?

1 个答案:

答案 0 :(得分:12)

如果您只想为选定的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);
}

这样您就不需要在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);
}

您也可以在{{3>} 例外格式部分

中了解相关信息