Need a user's IP address in Laravel? Here are three ways to grab it, depending on your preference.
I'll admit that 3 ways is just a single way to fetch the user's IP address, just using three different styles depending on how you write code or what situation you find yourself in.
Every method pulls from the same place — Laravel's Request
class. Let's take a look.
This is my preferred method for fetching the user's IP address in Laravel, since it doesn't depend on having the underlying Request
class pulled in anywhere — we're just using the helper!
request()->ip() // 127.0.0.1
Suppose you're fetching the IP address from a controller and you have access to either the Request
class or a Laravel form request (which extends the Request
class).
In that case, you can directly access the ip
method this way.
class SomeController extends Controller
{
public function store(Request $request)
{
$request->ip(); // 127.0.0.1
}
}
As mentioned, the same method works if you're using a form request:
class SomeController extends Controller
{
public function store(SomeStoreRequest $request)
{
$request->ip(); // still 127.0.0.1
}
}
You can also use the Request
facade to access the underlying ip
method.
use Illuminate\Support\Facades\Request;
Request::ip(); // 127.0.0.1
If you prefer facades, this is the option for you. Although, you may prefer using the request()
helper (discussed above), which doesn't require an import and can look a little neater.
There we go! (Kind of) 3 ways to fetch the IP address of a visitor in Laravel. Of course, all using the same underlying method!