您的位置:首页 > 技术中心 > php框架 >

Laravel中FormRequest中重写错误处理的介绍(代码示例)

时间:2019-01-09 10:00

本篇文章给大家带来的内容是关于Laravel中FormRequest中重写错误处理的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

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

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

3168146294-5c354bdda6974_articlex.png

代码如下

<?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]]));

    }


}

重写了failedValidation方法,将抛出错误处理为了json格式的。
然后在自定义的处理验证类中,继承该类就行了,
如:RegisterForm

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

    }



}

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

1651441504-5c354bdf7c0d5_articlex.png

以上就是Laravel中FormRequest中重写错误处理的介绍(代码示例)的详细内容,更多请关注gxlsystem.com其它相关文章!

本类排行

今日推荐

热门手游