Laravel 5.2-使用API进行验证 [英] Laravel 5.2 - Validation with API
问题描述
我正在使用Laravel 5.2通过REST JSON API进行验证.
I am using Laravel 5.2 for validation with a REST JSON API.
我有一个UserController
,它扩展了Controller并使用了ValidatesRequests
特性.
I have a UserController
that extends Controller and uses the ValidatesRequests
trait.
示例代码:
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:4|max:72',
'identifier' => 'required|min:4|max:36',
'role' => 'required|integer|exists:role,id',
]);
这引发异常,因此在我的Exceptions/Handler.php
中,我有以下代码:
This throws an exception, so in my Exceptions/Handler.php
I have this code:
public function render($request, Exception $e)
{
return response()->json([
'responseCode' => 1,
'responseTxt' => $e->getMessage(),
], 400);
}
但是,验证responseTxt
时始终为:
Array
(
[responseCode] => 1
[responseTxt] => The given data failed to pass validation.
)
我过去曾经使用过Laravel 4.2,并记得验证错误,其中提供了有关验证失败的更多详细信息.
I have used Laravel 4.2 in the past and remember the validation errors providing more detail about what failed to validate.
我怎么知道哪个字段验证失败,为什么?
How can I know which field failed validation and why?
推荐答案
在Laravel 5.2中,validate()方法抛出Illuminate \ Validation \ ValidationException,因此,如果要获取响应,请使用 getResponse() >而是getMessage().
In Laravel 5.2 validate() method throws a Illuminate\Validation\ValidationException, so if you want to get the response use getResponse() instead getMessage().
例如,处理此异常的一种简单方法可能是执行以下操作:
For example, an easy way to handle this exception could be doing something like this:
try{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:4|max:72',
'identifier' => 'required|min:4|max:36',
'role' => 'required|integer|exists:role,id'
]);
}catch( \Illuminate\Validation\ValidationException $e ){
return $e->getResponse();
}
这篇关于Laravel 5.2-使用API进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!