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
You can install Laravel 12 using the command below. Make sure Composer is installed.
laravel new laravel12-ipaddress
Now let’s create a controller where we’ll write the logic to get the IP address.
php artisan make:controller IPAddressController
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);
}
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.
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.
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: