【问题标题】:Laravel 5.2 - Validation with APILaravel 5.2 - 使用 API 进行验证
【发布时间】:2016-08-30 12:16:16
【问题描述】:

我正在使用 Laravel 5.2 通过 REST JSON API 进行验证。

我有一个 UserController 扩展 Controller 并使用 ValidatesRequests 特征。

示例代码:

$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 中有这个代码:

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,并记得验证错误提供了有关无法验证的更多详细信息。

我如何知道哪个字段未通过验证以及为什么?

【问题讨论】:

    标签: php validation laravel laravel-5


    【解决方案1】:

    如果请求需要 JSON,则会抛出 ValidationException,它会呈现为单个通用消息。

    不使用 validate() 方法,而是手动调用验证器,例如:

    $validator = Validator::make($request->all(), [
        'email'         => 'required|email',
        'password'      => 'required|min:4|max:72',
        'identifier'    => 'required|min:4|max:36',
        'role'          => 'required|integer|exists:role,id',
    ]);
    if ($validator->fails()) {
        return new JsonResponse(['errors' => $validator->messages()], 422);
    }
    

    https://laravel.com/docs/5.2/validation#manually-creating-validators

    顺便说一句,我建议使用 422 HTTP 状态代码而不是 400。400 通常意味着格式错误的语法。导致验证错误的东西通常意味着语法正确,但数据无效。 422 表示“无法处理的实体” https://www.rfc-editor.org/rfc/rfc4918#section-11.2

    【讨论】:

      【解决方案2】:

      在 Laravel 5.2 中,validate() 方法会抛出 Illuminate\Validation\ValidationException,因此如果您想获得响应,请使用 getResponse() 而不是 getMessage()。

      例如,处理此异常的一种简单方法是执行以下操作:

      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();
      }
      

      【讨论】:

        猜你喜欢
        • 2017-07-04
        • 2017-06-02
        • 2016-04-23
        • 1970-01-01
        • 2017-01-19
        • 2016-09-15
        • 1970-01-01
        • 2017-07-03
        • 1970-01-01
        相关资源
        最近更新 更多