Format FormRequest Validation Error Response

笑着哭i 提交于 2019-12-11 06:48:34

问题


With reference to this stack question and answer I'm trying to format the response of my error validations to a more simplified format...thus in a custom App\Http\Requests\CustomRequest I have

public function rules()

{
    return [
        'amt' => 'required|numeric|min:1000',
        'year' => 'required|numeric|min:' . date_format(new \DateTime, 'Y'),
        'user_id' => 'required',
        'ratio' => 'required'
    ];
}

public function response(array $errors)
   {
       if ($this->expectsJson()) {
          return response()->json(['messsage'=>'Cannot Validate','errors'=> $errors]);
       }

       return $this->redirector->to($this->getRedirectUrl())
                                       ->withInput($this->except($this->dontFlash))
                                       ->withErrors($errors, $this->errorBag);
   }

/**
    * Format the errors from the given Validator instance.
    *
    * @param  \Illuminate\Contracts\Validation\Validator  $validator
    * @return array
    */
   protected function formatErrors(Validator $validator)
   {
       return [];
   }

in my controller I have

/**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return Response Header 201
     */
    public function store(CustomFormRequest $request)
    {

        $requestData = $request->all();
        Budget::create($requestData);

        return response([], 201);
    }

According to the laravel docs I just have to "typehint" the the request. However my response is always.

{"id":"validation_failed","message":"Validation failed.","meta":{"errors":{"amt":[{"rule":"min.numeric","message":"The amt must be at least 1000.","parameters":["1000"]}]}}}

Which doesn't make sense if I'm changing the response format. What i need is

{"id":"validation_failed","message":"Validation failed.","errors":[{"amt":{"message":"The amt must be at least 1000."}}]}

I'm not sure what I should be doing at this point. What else is there?


回答1:


Side-channel communication (IRC) revealed that Kendall is using lanin/laravel-api-exceptions. This package has a custom exception handler that changes Laravel's built-in ValidationException into a custom exception class, and custom output handling. A hint that the output wasn't generated by Laravel can be the meta key in the json output, Laravel does not produce that.

The question mentions the response(array $errors) and the formatErrors(Validator $validator) methods of FormRequest, but these are not used by this package.

The json result of validation failures can be modified by overriding the custom exception handler's renderForApi method, check for ValidationFailedApiException, and return a custom response for these.




回答2:


To have a custom error message I suppose you are looking for the messages method. On that method, just return an array.

Example: ['fieldName.rule' => 'Custom message']

See: https://laravel.com/api/5.3/Illuminate/Foundation/Http/FormRequest.html#method_messages

Bonus: if you want to name the field name also just make a attributes method.

See: https://laravel.com/api/5.3/Illuminate/Foundation/Http/FormRequest.html#method_attributes



来源:https://stackoverflow.com/questions/42100798/format-formrequest-validation-error-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!