Laravel自定义错误验证JSON响应对象到数组

时间:2018-08-28 12:39:15

标签: php json laravel laravel-5

如果用户未填写必填字段,我会尝试为注册表单创建API。验证程序以对象格式显示错误,但是i需要数组格式的json响应。

$validator = Validator::make($request->all(), [ 
    'name' => 'required', 
    'mobile' => 'required', 
    'address' => 'required', 
]);
if ($validator->fails()) { 
    return response()->json(['error'=>$validator->errors()], 401);            
}
  

当前输出为

 {
    "error": {
        "name": [
            "The name field is required."
        ],
        "mobile": [
            "The mobile field is required."
        ],
        "address": [
            "The addressfield is required."
        ]
    }
}
  

预期产量

{
  "error": [
      "The name field is required.",
      "The mobile field is required.",
      "The address field is required."
  ]
}

2 个答案:

答案 0 :(得分:0)

要获得预期结果,请使用$validator->errors()循环迭代foreach()并将所有值压入数组,然后返回该数组,如:

$err = array();
foreach ($validator->errors() as $error)
{
    array_push($err, $error);
}

return response()->json(['error'=>$err], 401);

答案 1 :(得分:0)

正确的答案是这个:

$err = array();

        foreach ($validator->errors()->toArray() as $error)  {
            foreach($error as $sub_error){
                array_push($err, $sub_error);
            }
        }
        return ['errors'=>$err];

添加了内部foreach,因为可能一个输入的多个验证条件失败(例如:密码为too shorttoo weak)。

并且Mayank Pandeyz的答案for循环不会重复,因为直到我们在toArray()的末尾添加$validator->errors()