How to Get Client IP Address in Laravel 10?

Sovary July 18, 2023 455
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him