How to get client ip address in laravel?

Member

by lew , in category: PHP Frameworks , 6 months ago

How to get client ip address in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 6 months ago

@lew 

To get the client IP address in Laravel, you can use the getRequest() method to get the current request object and then use the ip() method on the request object to get the IP address. Here's an example of how you can do it:

1
2
3
4
5
6
7
use IlluminateHttpRequest;

public function index(Request $request)
{
    $ip = $request->ip();
    // Use the $ip variable as needed
}


You can also use the getClientIp() method to get the IP address directly from the request object, like this:

1
2
3
4
5
6
7
use IlluminateHttpRequest;

public function index(Request $request)
{
    $ip = $request->getClientIp();
    // Use the $ip variable as needed
}


Both methods will retrieve the client's IP address, but using getClientIp() method can handle situations where the client IP is behind a proxy or load balancer.