讨论数量:
表单验证失败会抛出 ValidationException
,Laravel 异常处理会针对请求头返回相应的结果:
如果请求头的 accept
含有 json
就会返回 JsonResponse
:
框架自带的响应格式:
如果需要变更响应格式,更改 \App\Exceptions\Handler::render
方法:
public function render($request, Exception $exception)
{
if($exception instanceof ValidationException){
return response()->json([]);// 从 exception 中获取错误信息
}
return parent::render($request, $exception);
}
参考文档:表单验证《Laravel 8 中文文档》 文档中的原文:
所以,验证规则是如何运行的呢?你所需要做的就是在控制器方法中类型提示传入的请求。在调用控制器方法之前验证传入的表单请求,这意味着你不需要在控制器中写任何验证逻辑:
手动创建验证器
$validator = Validator::make($request->post(), [
'number' => ['required', 'integer', 'between:1,100'],
], [
'number.required' => '请输入数量',
'number.between' => '数量必须在1-100之间'
]);
表单验证失败会抛出 ValidationException
,Laravel 异常处理会针对请求头返回相应的结果:
如果请求头的 accept
含有 json
就会返回 JsonResponse
:
框架自带的响应格式:
如果需要变更响应格式,更改 \App\Exceptions\Handler::render
方法:
public function render($request, Exception $exception)
{
if($exception instanceof ValidationException){
return response()->json([]);// 从 exception 中获取错误信息
}
return parent::render($request, $exception);
}
<?php
namespace App\Apis\V1\Http\Requests;
class ChargeDetailsRequest extends BaseRequest
{
public function rules()
{
return [
'from' => 'required|date_format:Y-m-d H:i:s',
'to' => 'required|date_format:Y-m-d H:i:s',
'entry_to_my' => 'required|in:false,true',
'cdw' => 'required|in:false,true',
'pai' => 'required|in:false,true',
'add_drivers' => 'string',
];
}
}
<?php
namespace App\Apis\V1\Http\Requests;
use App\Exceptions\Api\ApiRequestException;
use Illuminate\Foundation\Http\FormRequest;
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;
}
/**
* @param Validator $validator
* @throws ApiRequestException
*/
protected function failedValidation(Validator $validator)
{
$error = $validator->errors()->all();
throw new ApiRequestException($error[0]);
}
}
表单验证失败会抛出
ValidationException
,Laravel 异常处理会针对请求头返回相应的结果:如果请求头的
accept
含有json
就会返回JsonResponse
:框架自带的响应格式:

如果需要变更响应格式,更改
\App\Exceptions\Handler::render
方法: