How to get IP address & location info in laravel?

How to get IP address & location info in laravel?

Hello Devs,

Today we will discuss about how to get user IP address and location info in Laravel. This tutorial goes into detail on how to get client IP and location information in Laravel application. We will get user IP and location information without any package. We will learn how to get client IP address of website user and location info with curl request in Laravel. Let's discuss about how to get IP address for website user and location in Laravel.

We will use a free API to get IP address of website user and location information, you can get that API here. You can get these information with any Laravel package also but in this tutorial we will get this with an API instead of any package.

Step 1: Get API Token

First, we need to create an account to get API. After creating the account you can get your api access token in the token tab.

Blog Images

Step 2: Get IP address & Find location

In laravel, we can get user IP address with request If you know IP address then you can get location information by passing IP address in API url. Let's see below example.

Route::get('/get/location',function(Request $request){
	// get IP address
	$IP = $request->ip();
	
	// run curl request to find location info with ip address
    $ch = curl_init('https://ipinfo.io/$IP?token=your-api-access-token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // execute!
    $response = curl_exec($ch);
    $result = json_decode($response);
    dd($result);
});

You will get all other information along with IP address.

{
  "ip": "119.157.82.117"
  "city": "Faisalabad"
  "region": "Punjab"
  "country": "PK"
  "loc": "24.9170,67.0875"
  "org": "AS141361 Bliss Communication Network (Pvt) Ltd"
  "postal": "75300"
  "timezone": "Asia/Karachi"
}

Note:

If you run this API without giving any IP address then it will return server IP address and location information everytime. To get correct client information you must need to add client IP address in API call. 

Conclusion

We have learned how to get IP address of website user and then from it's IP address how to get location information of website user in laravel without any package. We have used an API to get all required data instead use of any laravel package.

I hope, it will help you.

Happy Learning :)

Leave a Comment

Your email address will not be published. Required fields are marked *

Go To Top
×