【问题标题】:Validating an API request in Laravel 5.1在 Laravel 5.1 中验证 API 请求
【发布时间】:2015-09-24 16:09:36
【问题描述】:

我正在使用 laravel 5.1 创建一个简单的 api 在表中创建一行并返回新创建的行的 id。

我可以这样做,但是在验证时我不确定该怎么做。

例如 transaction_request 表 id|order_id|customer_id|amount

只需要 order_id 和 customer_id 的验证规则

我请求这个的 uri 是 http://localhost:8000/api/v1/transactionRequests?order_id=123&customer_id=&amount=3300

请注意,customer_id 未定义。用户返回以下 json。

{
"error": {
    "code": "GEN-WRONG-ARGS",
    "http_code": 400,
    "message": "{\"customer_id\":[\"The customer_id field is required.\"]}"
    }
}

查看消息:使用那些“\”,我该如何解决。我知道,这是因为,我在控制器中使用了以下验证方法会引发异常

public function validateRequestOrFail($request, array $rules, $messages = [], $customAttributes = [])
{
    $validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);

    if ($validator->fails())
    {
        throw new Exception($validator->messages());
    }
}

我使用 catch 来处理它,如下所示

try {
        if(sizeof(TransactionRequest::$rules) > 0)
            $this->validateRequestOrFail($request, TransactionRequest::$rules);

    } catch (Exception $e) {

        return $this->response->errorWrongArgs($e->getMessage());

    }

errorWrongArgs 定义如下

public function errorWrongArgs($message = 'Wrong Arguments')
{
    return $this->setStatusCode(400)->withError($message, self::CODE_WRONG_ARGS);
}

public function withError($message, $errorCode)
{
    return $this->withArray([
        'error' => [
            'code' => $errorCode,
            'http_code' => $this->statusCode,
            'message' => $message
        ]
    ]);
}

我希望响应如下所示(顺便说一句,我使用的是 ellipsesynergie/api-response 库而不是默认响应类,因为我使用的是 chrisbjr/api-guard)

{
"error": {
    "code": "GEN-WRONG-ARGS",
    "http_code": 400,
    "message": {
             "customer_id": "The customer_id field is required."
        }
    }
}

【问题讨论】:

  • return $this->response->errorWrongArgs(json_decode($e->getMessage(),true)); 我使用了 json_decode 并得到“customer_id”:[“customer_id 字段是必需的。”]。问题在于消息存储在 $validator->messages() 中的方式,它是一个 MessageBag 对象,但我不确定如何将其转换为适合 json 响应的格式。
  • 也就是说,是否需要在 api 响应中给出这样的特定消息,我可以用一个简单的消息来做,比如“验证失败”。

标签: validation api exception-handling laravel-5.1


【解决方案1】:

是的,问题在于我对 $validator->messages() 返回的内容的理解,它返回一个更像 Json 对象的 MessageBag 对象。 Exception() 需要一个字符串消息。因此,它通过将引号字符转义为 \" 来将 Json 视为字符串。对此的解决方案是将 Json 字符串传递给 Exception 方法,但在捕获它之后,我使用 json_decode 将 Json 字符串转换为数组,然后由我的响应类。

throw new Exception($validator->messages());

return $this->response->errorWrongArgs(json_decode($e->getMessage(),true));

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 2017-06-02
    • 2017-10-01
    • 2018-09-13
    • 2023-03-14
    • 2016-05-22
    • 2017-08-28
    • 2015-11-07
    • 2016-01-20
    相关资源
    最近更新 更多