user image

Eslam Zedan
Published in : 2022-03-02

Get user location (city - country) from his IP address

Laravel

Hello,

I want to get the user location (city - country) from his IP address in Laravel so I can store where he logged in 

any recommendations?

Comments

Mohamed Atef Date : 2022-03-03

Best answers

46

Best answers

46

You can use http://ipinfo.io/ to get the location details using the IP address in Laravel you can use it easily using GET request to the endpoint like 

http://ipinfo.io/[IP_ADDRESS]?token=TOKEN_HERE

so in Laravel you can use $req->ip(); to get the IP address of the requests then using HTTP class you can it the endpoint with GET method so the controller will be like 

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Http;

class users_controller extends Controller {

    protected function create(Request $req){
        $ip = $req->ip();
        $res = Http::get('http://ipinfo.io/'.$ip.'?token=[YOUR_TOKEN]');
        $city = $res['city'];
        $country = $res['country'];
        return $city .' '. $country;
    }
}

Good luck 

Shilpa Date : 2022-03-03

Best answers

10

Best answers

10

There are lots of IP API provider services available in the market. You can use any of them, but make sure below things.

  1. How many hits they are giving? free vs paid hits
  2. What is the price for each hit?
  3. What is your user interaction ratio and how many hits do you need per day?
  4. Check the accuracy before buying a package or going live with the API!
  5. Check the stability of the service you are using and user reviews for that website. Some might get down within a year or two, so avoid it.
  6. Check if the website you are choosing is available in your target country or not!

Here is the list of popular IP, City, State, Country, and ISP providers:

https://ipapi.co/ ←----- Recommended

https://ipapi.com/

https://ip-api.com/

https://ipwhois.io/

For laravel code, you can use answer given by Mohamed Atef above.

Hope above given information will help you.

 

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

[SOLVED] No application encryption key has been specified.
Publish date: 2021-05-17 | Comments: 2
What's the best approach to use Elasticsearch with Larave?
Publish date: 2022-02-21 | Comments: 2
Laravel clear cache files manually
Publish date: 2022-03-02 | Comments: 2
tymon/jwt-auth 0.5.12 requires illuminate/support ~5.0
Publish date: 2022-02-18 | Comments: 2