如何验证 REST Lumen/Laravel 请求中的参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44109421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate params in REST Lumen/Laravel request?
提问by wujt
Route:
$app->get('/ip/{ip}', GeoIpController::class . '@show');
路线:
$app->get('/ip/{ip}', GeoIpController::class . '@show');
How to validate ip's properly? I've tried to inject Request
object in show
method, but wasn't able to solve this. I want to stick with REST
, so using URL
parameters is not solution for me. I use it for API
purposes, so status code as response would be appropriate.
如何正确验证ip?我试图Request
在show
方法中注入对象,但无法解决这个问题。我想坚持使用REST
,所以使用URL
参数对我来说不是解决方案。我将它用于API
目的,因此状态代码作为响应是合适的。
Also tried that way:
也试过这样:
$app->bind('ip', function ($ip) {
$this->validate($ip, [
'ip' => 'required|ip',
]);
});
EDIT:
The answer below is correct, I've found more info about requests
in documentation:
编辑:下面的答案是正确的,我requests
在文档中找到了更多信息:
Form requests are not supported by Lumen. If you would like to use form requests, you should use the full Laravel framework.
Lumen 不支持表单请求。如果你想使用表单请求,你应该使用完整的 Laravel 框架。
In other words, you cannot use custom requests
via injection in constructors in Lumen.
换句话说,您不能requests
在 Lumen 的构造函数中使用自定义通过注入。
回答by Sandeesh
The validate
method takes the request object as the first parameter. Since you're passing the ip in the route, you need to create a custom validator.
该validate
方法将请求对象作为第一个参数。由于您在路由中传递 ip,因此您需要创建一个自定义验证器。
public function show($ip)
{
$data = ['ip' => $ip];
$validator = \Validator::make($data, [
'ip' => 'required|ip'
]);
if ($validator->fails()) {
return $validator->errors();
}
return response()->json(['All good!']);
}
Edit : This is all laravel does under the hood. You could basically you this function directly to validate the ip and save a lot of effort.
编辑:这就是 Laravel 在幕后所做的一切。您基本上可以直接使用此功能来验证ip并节省大量精力。
protected function validateIp($ip)
{
return filter_var($ip, FILTER_VALIDATE_IP) !== false;
}