php Laravel 4 - 如何将所有字段的所有验证错误消息作为 JSON 结构返回?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19422259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 19:26:36  来源:igfitidea点击:

Laravel 4 - how to return all validation error messages for all fields as a JSON structure?

phplaravellaravel-4

提问by mtmacdonald

I'm upgrading from Laravel 3 to Laravel 4. My app has some AJAX-only forms that are rendered client-side (i.e. there are no server-side views). Therefore, instead of passing validation errors to views with the withErrors()method, I've been returning the validation error objects to the client as JSON structures.

我正在从 Laravel 3 升级到 Laravel 4。我的应用程序有一些仅在客户端呈现的 AJAX 表单(即没有服务器端视图)。因此,我没有使用withErrors()方法将验证错误传递给视图,而是将验证错误对象作为 JSON 结构返回给客户端。

In Laravel 3, I had this:

在 Laravel 3 中,我有这个:

$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
  return json_encode($validation->errors);
}
//else handle task

But in Laravel 4, the error messages are protected:

但是在 Laravel 4 中,错误消息受到保护:

$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
  var_dump($validation->messages());
  return json_encode($validation->messages());
}
//else handle task

var_dump($validation->messages())returns:

var_dump($validation->messages())返回:

object(Illuminate\Support\MessageBag)[333]
  protected 'messages' => 
    array (size=1)
      'delete_confirm_password' => 
        array (size=1)
          0 => string 'The delete confirm password field is required.' (length=46)
  protected 'format' => string ':message' (length=8)

json_encode($validation->messages)returns

json_encode($validation->messages)返回

{}

Question:how do I return all the validation error messages for all fields as a JSON structure in Laravel 4?

问题:如何在 Laravel 4 中将所有字段的所有验证错误消息作为 JSON 结构返回?

采纳答案by mtmacdonald

I discovered it was possible to use the toArray()method:

我发现可以使用toArray()方法:

return json_encode($validation->messages()->toArray()); 

回答by Andreyco

Simply use toJson()method.

简单地使用toJson()方法。

return $validator->messages()->toJson();

回答by Elia Weiss

Here is another way that let u add HTTP code to the response:

这是让您向响应添加 HTTP 代码的另一种方法:

return Response::json($validation->messages(), 500);

回答by Todor Todorov

I think that this is the Laravel way to get the error messages. There are special methods to get them. So here how I do this stuff:

我认为这是 Laravel 获取错误消息的方式。有特殊的方法来获取它们。所以在这里我如何做这些事情:

return Response::json($validator->errors()->getMessages(), 400);

This produces output in the following format:

这将产生以下格式的输出:

{
"field_name": [
     "Error message"
     ]
}