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