Laravel 验证错误自定义响应格式 [英] Laravel Validation Error customise format of the Response

查看:30
本文介绍了Laravel 验证错误自定义响应格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 L5 表单请求,我不只是喜欢 Taylor!好吧,我正在执行一些 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.

我想将关于验证错误的响应格式化为这样的内容

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 验证错误自定义响应格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆