简体   繁体   English

Laravel 5.4中的api验证

[英]Api validation in laravel 5.4

Hi guys I'm working on API but I need to validate some data at backend, in this case, we only need a postman to send parameters and headers. 嗨,大家好,我正在研究API,但我需要在后端验证一些数据,在这种情况下,我们只需要一个邮递员即可发送参数和标头。

All is working fine now but I need more useful data in each request, Laravel has by default a Validator Form Request Validation , but I don´t know how to use at API side. 现在一切正常,但是我在每个请求中都需要更多有用的数据,Laravel默认情况下具有Validator Form Request Validation ,但是我不知道如何在API端使用。

I need to send the error message in JSON to Postman. 我需要将JSON中的错误消息发送给Postman。

I found two options, one, make validations into a controller but seems to much code and the other make a php artisan make:request StoreObjectPost and then import the request into the controller and change the request of the store method, which one do you recommend, Ty! 我发现了两种选择,一种是对控制器进行验证,但似乎有很多代码,另一种则使php artisan make:request StoreObjectPost ,然后将请求导入控制器并更改store方法的请求,您推荐哪一种,Ty!

You could instantiate the validator yourself like this: 您可以自己实例化验证器,如下所示:

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

Hope this may help you 希望这对您有帮助

You should override response(array $errors) method of FormRequest . 您应该重写FormRequest response(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);
}

I prefer the second option. 我更喜欢第二种选择。 We will be able to keep our controller clean that way, even when we use many validations for the data or using custom error message in the validation 即使我们对数据使用许多验证或在验证中使用自定义错误消息,我们也可以保持控制器整洁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM