Laravel Validation Error customise format of the Response

后端 未结 4 946
遇见更好的自我
遇见更好的自我 2020-12-17 01:42

I am working with L5 Form Requests and don\'t I just love Taylor! Well, I am doing some AJAX requests and I still want to retain my form requests. The problem is that in the

4条回答
  •  Happy的楠姐
    2020-12-17 02:06

    Currently accepted answer no longer works so i am giving an updated answer.

    In the revelent FormRequest use failedValidation function to throw a custom exception

    // add this at the top of your file
    use Illuminate\Contracts\Validation\Validator; 
    use App\Exceptions\MyValidationException;
    
    protected function failedValidation(Validator $validator) {
        throw new MyValidationException($validator);
    }
    

    Create your custom exception in app/Exceptions

    validator = $validator;
        }
    
        public function render() {
            // return a json with desired format
            return response()->json([
                "error" => "form validation error",
                "message" => $this->validator->errors()->first()
            ], $this->code);
        }
    }
    

    This is the only way I found. If there is a better approach please leave a comment.

    This works in laraval5.5, I don't think this will work in laravel5.4 but i am not sure.

提交回复
热议问题