Posts Learn Components Snippets Categories Tags Tools About
/

How to get client IP address in Laravel 8

Learn how to get client IP address in Laravel 8 the easy way

Created on Nov 13, 2021

882 views

To easily get the client's IP address in Laravel 8 you can make use of the request object or use the helper method.
<?php

// request object
$request->ip();

// helper method
request()->ip();

Create Controller


This generally can be called from within a controller class and below is the full code example on how to achieve this.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index(Request $request)
    {
        dd($request->ip());
    }
}
Then for the route, you can define it like below.
<?php /routes/web.php

Route::get('getclientip', [\App\Http\Controllers\PostController::class, 'index']);

Laravel Get Client IP On Localhost

If you are still getting 127.0.0.1 as the IP, you need to add your "proxy", but be aware that you have to change it before going into production! For more details do read "Configuring Laravel Trusted Proxies". And add the following code to the TrustProxies class.
class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = '*';

Now request()->ip() gives you the correct IP address.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to get client IP address in Laravel 8

)