【问题标题】:Api validation in laravel 5.4laravel 5.4 中的 API 验证
【发布时间】:2017-12-17 15:23:12
【问题描述】:

大家好,我正在开发 API,但我需要在后端验证一些数据,在这种情况下,我们只需要一个邮递员来发送参数和标头。

现在一切正常,但我需要在每个请求中提供更多有用的数据,Laravel 默认有一个验证器Form Request Validation,但我不知道如何在 API 端使用。

我需要将错误消息以 JSON 格式发送给 Postman。

我找到了两个选项,一个是在控制器中进行验证,但代码似乎很多,另一个是 php artisan make:request StoreObjectPost 然后导入请求进入控制器并更改 store 方法的请求,你推荐哪一个,Ty!

【问题讨论】:

    标签: php json laravel api validation


    【解决方案1】:

    您可以像这样自己实例化验证器:

    $validator = Validator::make($request->all(), [
        'name' => 'min:5'
    ]);
    
    // then, if it fails, return the error messages in JSON format
    if ($validator->fails()) {    
        return response()->json($validator->messages(), 200);
    }
    

    【讨论】:

      【解决方案2】:
      $PostData = Input::all();
      $Validator = Validator::make(array(
           'name' => $PostData['name']
            ), array(
            'name' => 'required'
      ));
      if ($Validator->fails()) { //if validator is failed
         return false;
      } else {
            // do some thing here
      }
      

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        您应该覆盖FormRequestresponse(array $errors) 方法。

        public function response(array $errors)
        {
            //Format your error message
        
            if ($this->expectsJson()) {
                return new JsonResponse($errors, 422);
            }
        
            return $this->redirector->to($this->getRedirectUrl())
                                            ->withInput($this->except($this->dontFlash))
                                            ->withErrors($errors, $this->errorBag);
        }
        

        【讨论】:

          【解决方案4】:

          我更喜欢第二种选择。即使我们对数据使用许多验证或在验证中使用自定义错误消息,我们也将能够保持控制器清洁

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-06-15
            • 2017-10-19
            • 1970-01-01
            • 2017-11-13
            • 2018-01-12
            • 2017-07-12
            • 2017-11-20
            • 1970-01-01
            相关资源
            最近更新 更多