How to Get Client IP Address in Laravel 10?

Sovary July 18, 2023 434
1 minute read

Topic today we are talking about how to get client ip address in Laravel. We will learn simply with example to get ip address which is request from client side. Actually, when making request from client there is one specifically address which request to server and server to respond them back through the IP address. 

The below examples I will give in different ways to get client IP Address in laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 application.

Example #1 - Using Request Object and Ip() function

In this example, we are defining an ip() function that accepts a Request instance as an argument. Inside index() function, we are calling the ip() function on the Request instance to retrieve the client’s IP address. Then we are dump die info which contain in variable ip.

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class UserController extends Controller
{
    
    public function index(Request $request)
    {
        $ip = $request->ip();   
        dd($ip);
    }
}

Example #2 - Using getClientIp()

This is another method to get client ip address with different function. We call getClientIp() function from instance Request parameter to retrieve Ip which was sent by client. 

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class UserController extends Controller
{
    
    public function index(Request $request)
    {
        $ip = $request->getClientIp();
        dd($ip);
    }
}

Example #3 - Using class Request directly

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class UserController extends Controller
{
    
    public function index()
    {
        $ip = \Request::getClientIp();
        dd($ip);
    }
}

Or you can try below sample

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
  
class UserController extends Controller
{
    
    public function index()
    {
        $ip = \Request::ip();
        dd($ip);
    }
}

 Hope these methods above help you to complete your project today. Thanks for reading, have a nice day.

You may also like...

Laravel  PHP  Laravel 10 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him