Laravel Validation Error自定义响应格式 [英] Laravel Validation Error customise format of the Response
问题描述
我正在处理L5表格申请,我不只是喜欢泰勒!好吧,我正在执行一些AJAX请求,但我仍想保留我的表单请求.问题是,在发生验证错误的情况下,验证程序仅返回422错误响应并闪烁错误,但是无论验证是否成功,我的AJAX前端都希望服务器提供非常特定的响应格式.
I am working with L5 Form Requests and don't I just love Taylor! Well, I am doing some AJAX requests and I still want to retain my form requests. The problem is that in the case of a validation error the Validator just returns a 422 error response and flashes the errors, but my AJAX frontend expects a very specific format of response from server whether validation is successful or not.
我想将对Validation错误的响应格式化为
I want to format the response on Validation errors to something like this
return json_encode(['Result'=>'ERROR','Message'=>'//i get the errors..no problem//']);
我的问题是如何格式化表单请求的响应,尤其是当这不是全局的但在特定的表单请求上完成时.
我已经用谷歌搜索过,但没有看到非常有用的信息.深入研究Validator
类后,也尝试了此方法.
My problem is how to format the response for the form requests, especially when this is not global but done on specific form requests.
I have googled and yet not seen very helpful info. Tried this method too after digging into the Validator
class.
// added this function to my Form Request (after rules())
public function failedValidation(Validator $validator)
{
return ['Result'=>'Error'];
}
仍然没有成功.
推荐答案
在这里找到了答案: Laravel 5自定义验证重定向
您需要做的就是在表单请求中添加response()
方法,它将覆盖默认响应.在您的response()
中,您可以按照所需的任何方式进行重定向.
Found the answer here: Laravel 5 custom validation redirection
All you need to do is to add a response()
method in your form request and it will override the default response. In your response()
you can redirect in whatever fashion you want.
public function response(array $errors)
{
// Optionally, send a custom response on authorize failure
// (default is to just redirect to initial page with errors)
//
// Can return a response, a view, a redirect, or whatever els
return response()->json(['Result'=>'ERROR','Message'=>implode('<br/>',array_flatten($errors))]); // i wanted the Message to be a string
}
L5.5 +上的更新
此错误和可接受的解决方案是针对L5.4的.对于L5.5,请使用上述Ragas的答案(failedValidation()方法)
UPDATE on L5.5+
This error and the accepted solution was for L5.4. For L5.5, use Ragas' answer above (failedValidation() approach)
这篇关于Laravel Validation Error自定义响应格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!