In this blog post we will see how to get user current location details like (Country, Latitude and Longitude, City, Region, Postal Code) from user's IP Address.
We are going to use stevebauman/location
package.
This package is very useful to get the information about the users' location with the help of IP address.
Steps to follow:
- Install Package
- Register in Service Provider
- Usage
Step 1 - First install stevebauman/location
using composer
composer require stevebauman/location
Step 2 - Register the package in service provider which is in config/app.php
'providers' => [
....
Stevebauman\Location\LocationServiceProvider::class,
],
'aliases' => [
....
'Location' => 'Stevebauman\Location\Facades\Location',
]
After registration run below command to publish the configuration file it will create location.php
file in config
php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"
Step 3 - Now we will see how to use it in our project and get the information about users' location
use Stevebauman\Location\Facades\Location;
$location = Location::get() // it will retrieve default user location
if ($location) {
echo $location->countryName;
}
or we can retrieve users' location from specific IP Address
$location = Location::get('192.168.90.98');
Now with the help of below code we can retrieve users' location in laravel's blade file
$location->countryName
$location->countryCode
$location->regionName
$location->longitude
In this way you can have information about user's current location (also you can use - regionCode, cityName, zipCode, latitude).
😍 😍 Happy Reading 😍 😍
For more information about the package you can checkout it's Git Repo - https://github.com/stevebauman/location
Note: If you are going to use this kind of packages in your project make sure you have rights to access user's information and let user know that you want to track their information and let them choose to allow or deny it. 🙂 🙂
Top comments (2)
I think it is very important to mention that if you choose to do this, you need to ensure you comply with all legal requirements imposed on you by your regions of service. GDPR will NOT look kindly upon code like this unless you clearly explain to the user what you are collecting and why BEFORE you collect any of said data.
I personally consider code like this incredibly invasive and feel like my experience has shown me that there are many greater insights that can be gathered without sacrificing user privacy.
Yes you are right, I will consider and appreciate your suggestion.