0

我正在使用 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."
        }
    }
}
4

1 回答 1

0

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

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

return $this->response->errorWrongArgs(json_decode($e->getMessage(),true));
于 2015-07-09T13:14:40.620 回答