Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Request returning load balancer ip instead of client ip [duplicate]

Tags:

php

laravel

I'm facing an issue while getting the client ip address, when I try

request()->ip()

It returns me private server IP instead of client IP.

What can be a possible reason how to avoid this.

The reason behind asking this question is my payment gateway need a public IP to accept payments

like image 948
Moeen Basra Avatar asked Oct 28 '25 17:10

Moeen Basra


2 Answers

I actually found a solution which worked on all environments written in official documentation of Laravel here.

There is middleware called trusted proxies App\Http\Middleware\TrustProxies.

This middleware is responsible for resolving the proxies, it has a property called proxies.

I just set the proxies property as array of private IP's and it worked.

This is how it should looks like after modification.

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array|string
     */
    protected $proxies = [
        'x.x.x.x',
    ];

    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers = Request::HEADER_X_FORWARDED_ALL;
}

Don't forget to replace x.x.x.x with your private IP.

Now when I called the following function

request()->ip();

It gave me expected result.

like image 120
Moeen Basra Avatar answered Oct 31 '25 06:10

Moeen Basra


You can use

request()->header('X-Forwarded-For')

and check how your load balancer configured, maybe you forget about Original IP and X-Forwarded-For headers

like image 41
Dry7 Avatar answered Oct 31 '25 06:10

Dry7