Home / Snippets / How to get client IP address in Laravel 8
How to get client IP address in Laravel 8 cover

How to get client IP address in Laravel 8

924

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this