Get Client IP Address in Laravel 10

Get Client IP Address in Laravel 10

In Laravel, getting the IP address of a client can be important for various reasons, such as tracking user activity, implementing security measures, or personalizing user experiences. This tutorial explains how to get client IP address in Laravel 10.

Controller

Retrieving the client's IP address in a controller is a simple task. Just include the Request object as a method argument, and use the ip method to access the client's IP address.

app/Http/Controllers/TestController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class TestController
{
    public function index(Request $request): Response
    {
        $ip = $request->ip();

        return new Response($ip);
    }
}

Service - Method 1

In cases where direct access to the Request object might not be available, the service class can employ the Request facade for obtaining the client's IP address.

app/Services/TestService.php

<?php

namespace App\Services;

use Illuminate\Support\Facades\Request;

class TestService
{
    public static function process(): void
    {
        $ip = Request::ip();
    }
}

Service - Method 2

An alternative method to obtain the client's IP address, especially when direct access to the Request object is unavailable, involves utilizing the request helper function. This function provides an instance of the Request class, allowing the use of the ip method to retrieve the client's IP address.

app/Services/TestService.php

<?php

namespace App\Services;

class TestService
{
    public static function process(): void
    {
        $ip = request()?->ip();

        echo $ip;
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.