Laravel 表单验证错误返回json格式,重写failedValidation

1.新建一个基类BaseRequest,其他表单验证类继承此基类

php artisan make:request BaseRequest

2.重写验证失败方法

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;

class BaseRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    public function failedValidation(Validator $validator)
    {

        $error= $validator->errors()->all();
        throw  new HttpResponseException(response()->json(['code'=>400,'message'=>$error[0]]));
    }
}

 

上一篇:Laravel Middleware(中间件)


下一篇:Laravel密码验证改为MD5