How to get location from its IP Address using Laravel 5.4 with example

How to get location from its IP Address using Laravel 5.4 with example

In this tutorial, i will let you know how to get client ip address and their information from ip address in Laravel 5.4.

Many time you will need to get visitor's details for security, spam prevention etc. It's very easy to get visitor ip address and their location in PHP Laravel.

I am using "stevebauman/location" package to get location information like country name, country code, city name, zip code, latitude, longitude etc.

Now i am going to install "stevebauman/location" package by running following command from terminal :

composer require stevebauman/location

Now I will have to add service provider and alias in config/app.php file.

config/app.php
'providers' => [
    ....
    Stevebauman\Location\LocationServiceProvider::class,
],
'aliases' => [
    ....
    'Location' => Stevebauman\Location\Facades\Location::class,
]

Now publish the config file by running following command :

php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"

Now, i am ready to get visitor ip address and their location details.

In Laravel, I will get visitor ip address by using following line of code:

$ip= \Request::ip();

I am going to write code in my routes file to check whether it is working or not.

routes/web.php
  1. Route::get('get-location-from-ip',function(){
  2. $ip= \Request::ip();
  3. $data = \Location::get($ip);
  4. dd($data);
  5. });
Output :
Position {#190 ?
  +countryName: ""
  +countryCode: "IN"
  +regionCode: ""
  +regionName: "Uttar Pradesh"
  +cityName: "Noida"
  +zipCode: "201303"
  +isoCode: ""
  +postalCode: ""
  +latitude: "28.5700"
  +longitude: "77.3200"
  +metroCode: ""
  +areaCode: ""
  +driver: "Stevebauman\Location\Drivers\IpInfo"
}

Phone: (+91) 8800417876
Noida, 201301