How to get IP Detail of requested user in Laravel
There are different where we need users location detail that might be for security reason and for any product need. In such cases we need to fetch users address detail from the requested IP address of the user. so in this article we will basically learn how to fetch users ip address and fetch address detail from this ip. Following is the example code.
First we will fetch IP of requested user using the method request()->ip() then we will hit a third-party API with the IP address as parameter to get the address detail as shown below.
HomeController.php:-
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Schema; class HomeController extends Controller { public function getIPDetail(){ try{ $ip = request()->ip(); // it will fetch the ip of requested user $json = file_get_contents("http://ipinfo.io/{$ip}"); $details = json_decode($json); return $details; // return object of address detail } catch(\Exception $e){ return false; } } }
Output :-
Thank you for reading this article 😊
For any query do not hesitate to comment 💬