In this article we will learn to get user IP address in laravel. Client ip address is useful when we want to log the user request with ip address or wanted to know the location of user accessing our website. So in this article we will learn to use laravel inbuilt feature to get the client or user ip address.
You can use this example in any laravel 5, laravel 6, laravel 7, laravel 8 and also in laravel 9.
In php we need to do lots of stuff to fetch the real ip address of user but laravel we can fetch using request object as follow
request()->ip();
//or
\Request::ip();
So we can understand this with multiple examples as follow
Method 1: Get User IP address using global request function
In this method we will get the ip address using request()
global function of laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(Request $request)
{
$userIp = $request->ip();
dd($userIp);
}
}
Method 2: Get User IP Address using Custom Method
Sometimes when we are behind the load balancer then we will only get the server load balancer ip but we can get client ip using below method
Also Read : How to create custom logs file in laravel 8 / 9 ?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(Request $request)
{
$userIp = $this->getIp();
dd($userIp);
}
public function getIp(){
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $ip){
$ip = trim($ip); // just to be safe
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
return $ip;
}
}
}
}
return request()->ip(); // it will return server ip when no client ip found
}
}
Method 3: Get User IP address using Request Class
In this method we will get the ip address using request()
global function of laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(Request $request)
{
$userIp = Request::ip(); // $request->ip();
dd($userIp);
}
}