自定义Json对象以遵循特定格式

时间:2018-01-16 18:57:17

标签: php json laravel

在我的Laravel API中,电子邮件验证错误响应就像这样......

{
    "status": 409,
    "message": {
        "emailAddress": [
            "A user with email: my@email.com already exists."
        ]
    }
}

message值来自:$validator->messages();

现在,我想要的是获得像这种json格式的错误响应

{
      "status": 409,
      "message": "A user with email: my@email.com already exists"
}

如何通过进入$validator->messages();来完成这项工作?

3 个答案:

答案 0 :(得分:1)

如果您只想向用户返回第一个错误,则可以使用MessageBag作为Collection来处理,例如:

$validator = Validator::make($request->input(), [
  "email" => "...",
  "password" => "..."
]);

if ($validator->fails()) {
  $firstError = $validator->messages()->first();
  return response()->json(["status" => 409, "message" => $firstError], 409);
}

答案 1 :(得分:0)

对于幼虫5.6及以上,您可以使用以下解决方案。

在app / Exceptions / Handler.php下编辑文件并添加以下文件

protected function convertValidationExceptionToResponse(ValidationException $e, $request) {
    if ($e->response) {
        return $e->response;
    }

    $errors = $e->validator->errors()->getMessages();

    if ($request->expectsJson()) {
        return response()->json(["errors" => $this->error_to_json($errors)], 422);
    }

    return redirect()->back()->withInput(
        $request->input()
    )->withErrors($errors);
}

protected function error_to_json($errors) {
    $json_errors = $errors;

    $new_errors = array();
    foreach ($json_errors as $key => $value) {
        $new_errors[$key] = $value[0];
    }

    return $new_errors;
}

答案 2 :(得分:-1)

希望这能帮到你:

$validator = Validator::make($request->all(), [
            'email' => 'required|emails|exists:users',
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 409, 'message' => "A user with email: ' . $request->email . ' already exists"], 200);
        }