如何验证 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:01:24  来源:igfitidea点击:

How to validate params in REST Lumen/Laravel request?

laravelvalidationurlgetlumen

提问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 Requestobject in showmethod, but wasn't able to solve this. I want to stick with REST, so using URLparameters is not solution for me. I use it for APIpurposes, so status code as response would be appropriate.

如何正确验证ip?我试图Requestshow方法中注入对象,但无法解决这个问题。我想坚持使用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 requestsin 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 requestsvia injection in constructors in Lumen.

换句话说,您不能requests在 Lumen 的构造函数中使用自定义通过注入。

回答by Sandeesh

The validatemethod 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;
}