How to validate params in REST Lumen/Laravel request?
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.
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.
protected function validateIp($ip)
{
return filter_var($ip, FILTER_VALIDATE_IP) !== false;
}
wujt
Snooker, aviation and analog protography enthusiast. Burger lover. Currently works as PHP Software Engineer and assistant in school of photography in Cracow. Willing to become an airline pilot. Private projects can be found here: https://github.com/wojcikm
Updated on June 04, 2022Comments
-
wujt almost 2 years
Route:
$app->get('/ip/{ip}', GeoIpController::class . '@show');
How to validate ip's properly? I've tried to inject
Request
object inshow
method, but wasn't able to solve this. I want to stick withREST
, so usingURL
parameters is not solution for me. I use it forAPI
purposes, so status code as response would be appropriate.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:Form requests are not supported by Lumen. If you would like to use form requests, you should use the full Laravel framework.
In other words, you cannot use custom
requests
via injection in constructors in Lumen.