This article brings you an introduction to rewriting error handling in FormRequest in Laravel (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The default validate verification in the laravel framework, when handling errors, returns to the previous page by default, and only returns Json when it is ajax. If we want to always return Json, then we need to rewrite the error handling
as follows: Just create a new BaseRequest class in the Requests directory
The code is as follows
<?php /** * @文件名称: BaseRequest.php. * @author: daisc * @email: jiumengfadian@live.com * @Date: 2019/1/8 */ namespace App\Http\Requests\Front; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Exceptions\HttpResponseException; class BaseRequest extends FormRequest { public function failedValidation($validator) { $error= $validator->errors()->all(); // $error = $validator; throw new HttpResponseException(response()->json(['code'=>1,'message'=>$error[0]])); } }
rewrites the failedValidation
method and handles the thrown error in the json
format.
Then in the custom processing verification class, just inherit this class,
For example: RegisterForm
in
<?php namespace App\Http\Requests\Front; class RegisterForm extends BaseRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'phone'=>'required|regex:"^1\d{10}"', 'email' => 'required|email', 'password'=>'required|confirmed' ]; } public function messages() { return [ 'phone.required'=>'手机号不能为空', 'phone.regex'=>'请输入正确的手机号', ]; } }
When we call RegisterForm in the controller, The error message in Json format will be returned.
Regardless of whether it is AJAX
The above is the detailed content of Introduction to overriding error handling in FormRequest in Laravel (code example). For more information, please follow other related articles on the PHP Chinese website!