17

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

Route:POST:/entries/用于执行验证EntryController@store的用途。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课堂上做到这一点?

4

2 回答 2

40

如果您只想为选定的请求类自定义验证响应,则需要向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);
}

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

于 2017-10-10T15:21:04.067 回答
0

对于那些不想使用 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);
    }
于 2021-11-05T01:29:33.360 回答