How to Get Client IP Address in Laravel 12

When I started working with Laravel 12, one of the basic things I needed was to get the client’s IP address—either for logging, security, or just tracking who’s accessing the site. Luckily, Laravel makes this super easy.

In this short guide, I’ll show you how I get the user's IP address using Laravel’s built-in tools. No need for complex logic or external packages. Just simple, clean code that works.

Whether you’re building a login system, analytics tool, or blocking suspicious users, knowing how to grab the IP is a must.

Laravel 12 Get Client IP Address

How to Get Client IP Address in Laravel 12

 

Step 1: Install Laravel 12

You can install Laravel 12 using the command below. Make sure Composer is installed.

laravel new laravel12-ipaddress

 

Step 2: Create Controller

Now let’s create a controller where we’ll write the logic to get the IP address.

php artisan make:controller IPAddressController

 

Step 3: Add Logic to Get IP Address

Open the controller you just created and add the following code inside the method:

public function getClientIp(Request $request)
{
    $ip = $request->ip();
    dd($ip);
}

Don’t forget to import the Request class at the top:

use Illuminate\Http\Request;

Example:

public getClientIp()
{
    $ip = Request::ip();
    dd($ip); 
}

Example:

public function index(Request $request)
{
    $ip = $request->getClientIp();

     dd($ip); 
}

 

Step 4: Add Route

Now, add a route in your web.php file to access this method.

Route::get('/get-ip', [App\Http\Controllers\IPAddressController::class, 'getClientIp']);

That’s it! Now when you visit /get-ip in the browser, it will display your IP address.

 

Step 5: Get Real IP Behind Proxy

If your app is behind a proxy (like Nginx, Load Balancer, or Cloudflare), $request->ip() might not return the real IP. Use this:

$ip = $request->header('X-Forwarded-For');
if ($ip) {
    $ip = explode(',', $ip)[0]; // get first IP in the list
} else {
    $ip = $request->ip();
}

That checks the X-Forwarded-For header first, then falls back to default IP.

 

Step 6: Create Middleware to Log IP

If you want to log the IP address for every request, create a middleware:

php artisan make:middleware LogIpMiddleware

Now update the handle method:

public function handle($request, Closure $next)
{
    $ip = $request->header('X-Forwarded-For');
    if ($ip) {
        $ip = explode(',', $ip)[0];
    } else {
        $ip = $request->ip();
    }

    \Log::info('Client IP: ' . $ip);

    return $next($request);
}

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS