php request error,Laravel框架FormRequest中重写错误处理的方法

laravel 框架中默认的validate验证,在处理错误的时候,默认是返回上一页,当为ajax的时候才会返回Json。如果我们要一直返回Json的话,那么需要重写错误处理

如下:在Requests目录只用 新建BaseRequest类

9ea2e9b825e6e79b08b8019d0eed0b78.png

代码如下

/**

* @文件名称: 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]]));

}

}

重写了failedValidation方法,将抛出错误处理为了json格式的。

然后在自定义的处理验证类中,继承该类就行了,

如:RegisterForm中

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'=>'请输入正确的手机号',

];

}

}

当我们在控制器中调用RegisterForm的时候,就回返回Json格式的错误信息。

不分是否是AJAX

dcc3e136efc4be565acb3bc28086a873.png

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值