Get client IP address in Laravel 9

0
2409
Get client IP address in Laravel 9
Get client IP address in Laravel 9

In this post, I will show you a tip to get client IP address in Laravel 9, which even works when Laravel application is served behind proxies and load balancers.

By default, Laravel provides a way get client IP address by accessing the Request $request object:

$ip = request()->ip();

// or

$ip = request()->getClientIp();

This works, but when the Laravel app is served behind proxies and load balancers, the methods will only return the IP addresses of the proxies (or load balancers).

What should we do?

This is a very common case, when the Laravel application is behind Cloudflare, or Azure … The real client IP address is usually configured under X-Forwarded-For header. That means, we can retrieve the value by parsing the header :

$ip = $request->header('X-Forwarded-For');

There is another way to do it with Laravel 9 is to configure the App\Http\Middleware\TrustedProxies middleware:

namespace App\Http\Middleware;
 
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
 
class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var string|array
     */
    protected $proxies = [
        '192.168.1.1',
        '192.168.1.2',
        // ... add IP addresses of all proxies/load balancers here
    ];
 
    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO;
}

Once you update the $proxies property, you can retrieve real client IP address as usual with:

$ip = request()->ip(); 

$ip = request()->getClientIp();

That’s how you get client IP address in Laravel 9 properly.

Take a look at Laravel 9 docs if you need more information.

Have fun!