Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP Address Validation in Controller in Laravel 5

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

like image 873
Rizwan Ranjha Avatar asked Sep 12 '15 07:09

Rizwan Ranjha


2 Answers

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 !!!

like image 129
Rahul Hirve Avatar answered Oct 13 '22 05:10

Rahul Hirve


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.

like image 41
Phil Cross Avatar answered Oct 13 '22 03:10

Phil Cross