且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我如何在Laravel 5.5的FormRequest类中返回自定义响应?

更新时间:2023-11-17 13:14:58

您必须覆盖 failedValidation()方法,并使用所需的响应发出异常. 因此,您需要在 RequestForm 类中使用Illuminate\Contracts\Validation\ValidatorIlluminate\Http\Exceptions\HttpResponseException,并覆盖failedValidation()方法:

You have to override the failedValidation() method and issue the exception with the response what you want. So, you need to use Illuminate\Contracts\Validation\Validator and Illuminate\Http\Exceptions\HttpResponseException in the RequestForm class, and override the failedValidation() method:

protected function failedValidation(Validator $validator) { 
        throw new HttpResponseException(response()->json($validator->errors()->all(), 422)); 
}