I am trying to find a method to validate IP Address before submitting this to my database, I have tried a lot of Google Search but unable to do this in my Laravel Controller. Can you please help? Appreciated
Use inside your controller. Import validator class's namespace and try it for validating IP (IP4/ IP6) address. Laravel 5
and Laravel 5.X
public function update(Request $request)
{
$validator = Validator::make($request->all(), [
'ip_address' => 'required|ip'
]);
}
if ($validator->fails()) {
return "Invalid IP address!"
}
If you want to validate IP4 and IP6 respectively, then use following code.
'ip_address' => 'required|ipv4'
'ip_address' => 'required|ipv6'
Happy Coding !!!
You could do it either inside the controller itself:
public function update(Request $request)
{
// Get the current users IP address and add it to the request
$request->merge(['ip_address' => $_SERVER['REMOTE_ADDR']]);
// Validate the IP address contained inside the request
$this->validate($request, [
'ip_address' => 'required|ip'
]);
}
The $request->merge()
method will allow you to add items to the form request, and then you can just make a simple validate request on the IP only.
Alternatively, you could move all this to it's own Request class and inject that into the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With