在Laravel 5.4中,我们创建了一个类,我们所有的验证请求都继承了,因为我们需要自定义响应。
class APIRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Response on failure
*
* @param array $errors
* @return Response
*/
public function response(array $errors) {
$response = new ResponseObject();
$response->code = ResponseObject::BAD_REQUEST;
$response->status = ResponseObject::FAILED;
foreach ($errors as $item) {
array_push($response->messages, $item);
}
return Response::json($response);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
将扩展此范围的示例请求如下所示
class ResultsGetTermsRequest extends APIRequest
{
/**
* 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 [
'school_id' => 'required|integer',
'student_id' => 'required|integer',
];
}
}
然后我们的失败样本响应将是
{
"status": "FAILED",
"code": "400",
"messages": [
[
"The school id field is required."
],
[
"The student id field is required."
]
],
"result": []
}
然而,这对Laravel 5.5来说已经不再适用了。我注意到他们用failedValidation
的响应方法替换了。但是,当请求未经过验证时,这不会返回任何响应。如果我取消对print_r的注释,则会返回一些内容。似乎永远不会执行的唯一行是return语句。我错过了什么?
public function failedValidation(Validator $validator) {
$errors = (new ValidationException($validator))->errors();
$response = new ResponseObject();
$response->code = ResponseObject::BAD_REQUEST;
$response->status = ResponseObject::FAILED;
foreach ($errors as $item) {
array_push($response->messages, $item);
}
//print_r($response);
return Response::json($response);
}
答案 0 :(得分:5)
我想根据laravel upgrade指南,我们应该返回cookie
HttpResponseException
答案 1 :(得分:2)
如果你想从FormRequest类中执行此操作,可能是这样的:
protected function buildResponse($validator)
{
return response->json([
'code' => ResponseObject::BAD_REQUEST,
'status' => ResponseObject::FAILED,
'messages' => $validator->errors()->all(),
]);
}
protected function failedValidation(Validator $validator)
{
throw (new ValidationException($validator, $this->buildResponse($validator));
}
这会将您正在构建的响应添加到验证异常中。当异常处理程序尝试呈现它时,它将检查是否设置了response
,如果是,它将使用您传递的响应,而不是尝试将ValidationException转换为响应本身。
如果你希望“ALL”验证异常最终以这种格式呈现,我可能只是在异常处理程序级别执行此操作,因为异常处理程序已经能够将这些异常转换为Json,因此您可以更改处理程序本身的格式,基本上不必对默认的FormRequest进行任何调整。
答案 2 :(得分:0)
如果您使用的是laravel 5+,则可以通过覆盖invalid()
文件中的invalidJson()
或App/Exceptions/Handler.php
方法来轻松实现这一目标
就我而言,我正在开发API,并且api响应应采用特定格式,因此我在Handler.php
文件中添加了以下内容。
/**
* Convert a validation exception into a JSON response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
protected function invalidJson($request, ValidationException $exception)
{
return response()->json([
'code' => $exception->status,
'message' => $exception->getMessage(),
'errors' => $this->transformErrors($exception),
], $exception->status);
}
// transform the error messages,
private function transformErrors(ValidationException $exception)
{
$errors = [];
foreach ($exception->errors() as $field => $message) {
$errors[] = [
'field' => $field,
'message' => $message[0],
];
}
return $errors;
}