Sabbir Ahmed

Sabbir Ahmed

1 month ago

Laravel Geolocation API: Unlock the Power of PHP Geolocation Library

We often need to work with client’s IP address when developing applications. Laravel provides a great facility to get client IP on the go, it has Facade or Helper function to access user IP. But what if you need more than just IP address? What if you need to know more details like, user region, country, coordinates and other types of stuffs. In this tutorial, we will explore how we can achieve that using different popular package. 

The stevebauman/location package

 
There are several package available in laravel to extract IP details. Lets start with an example with stevebauman/location package. This package is very simple and easy to install. Lets install the package: 


composer require stevebauman/location

After successful installation, you need publish the configuration


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

  • How to get ip details? 


This package provides a facade called Stevebauman\Location\Facades\Location to get user IP information. We can access various information like country, city, latitude, longitude and many other information by just passing a IP number. Here is an example how we can use it in a controller to extract IP details


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stevebauman\Location\Facades\Location;

class IpDetailsController extends Controller
{
    public function getIpDetails(Request $request)
    {
        // Get the IP address from the request
        $ip = $request->ip();

        // Get the location details for the IP address
        $location = Location::get($ip);

        // Access specific details like country, city, latitude, longitude, etc.
        $country = $location->countryName ?? 'Unknown';
        $city = $location->cityName ?? 'Unknown';
        $latitude = $location->latitude ?? 'Unknown';
        $longitude = $location->longitude ?? 'Unknown';

        // Return the details as needed
        return response()->json([
            'ip' => $ip,
            'country' => $country,
            'city' => $city,
            'latitude' => $latitude,
            'longitude' => $longitude,
        ]);
    }
}

As you can see, we are passing the request IP in the get method from the package's Location facade. The response will generate all the corresponding data in the $location variable, where you can access the information by the property names. 

Thats it, Thats how simple it was to integrate and use this package. You can also get other information like zipCode, postalCode, timezone etc. 

  • Deep Dive into Location Facade 


The Location facade from the package can be used to extract various information about IP location details. Here are some key properties that you can use to get specific info by calling the get method from the facade: 

    • countryName: Get the country name from the request IP 
    • cityName: You can get the city name too 
    • latitude and longitude: Get coordinates of the location 
    • regionName: find the region name from which it is requested 
    • zipCode: Get the postal zip code information 
    • timezone: Get the timezone of the location. 

This details you can use for getting extensive information about users and use it where necessary. 

  • Comparing with Other Laravel Packages


Stevebauman package is a popular choice of course for IP geolocation in laravel. But there are other packages out there with comprehensive feature set such as torann/geoip. Lets explore some key details of this package so you can compare better of these packages: 

Data Sources: For the data source, Stevebauman package uses IPInfo as its primary data source. But the torann/geoip package uses multiple data source such as MaxMind which is great for extensive information. 

Customization: With torann/geoip package, you will find more options to customize as per your need such as choosing data sources and modify the behaviors of the result in various environments. 

Caching: You will get an efficient caching mechanism for both of the packages of course and they are very helpful to reduce number of API calls. But you would get more granular control over caching using torann/geoip.

Advanced Features: IP lookups using batch mode or defining a fallback location in case of IP lookup failure can be done using torann/geoip package.

The torann/geoip package


The torann/geoip package is another great choice for IP geolocation when developing application in Laravel. As discussed above, this package comes with much flexibility and can be installed and used in quick time. Lets see the installation and basic usage of this package: 

  • Lets install the package 


We will use laravel-geoip package today. First, lets install the package: 


            
composer require torann/geoip

Add ‘providers’ in config/app.php


            
'providers' => [

    \Torann\GeoIP\GeoIPServiceProvider::class,

]

And also aliases


            
'aliases' => [

    'GeoIP' => \Torann\GeoIP\Facades\GeoIP::class,

];

Then, please publish the the configuration files from vendor:



            
php artisan vendor:publish --provider="Torann\GeoIP\GeoIPServiceProvider"

Now we are done with installation. 

  • How would I get  ip details? 


To access IP details, you have to use geoip() function provided by this package: 


            
use Torann\GeoIP\Facades\GeoIP;

$ip = '8.8.8.8'; // Replace with the IP address you want to get details for

$location = geoip()->getLocation($ip);

// Accessing details
echo "Country: " . $location->country;
echo "City: " . $location->city;
echo "Latitude: " . $location->latitude;
echo "Longitude: " . $location->longitude;

You can also get other information with this package. For example, if you want to get the timezone's information, you can try like this: 


            
use Torann\GeoIP\Facades\GeoIP;

$ip = '8.8.8.8'; // Replace with the IP address you want to get the timezone for

$timezone = geoip()->getTimezone($ip);

echo "Timezone: " . $timezone;

  • About an error


Sometimes you might face an error related to caching when you try execute the package. In that case, you can try changing your cache driver to array from .env


            
CACHE_DRIVER=array


Handling Errors and Edge Cases


You will also have to keep in mind that, not every IP address can be extracted to location details properly. For example, if you use IP of your localhost (127.0.0.1), its not possible to find details for the IP. Also there can be other reasons, such as someone using VPN to make the request. For such cases you might receive no data, null, or empty as the package couldnt translate the IP properly. So ensure to keep a check or add condition in your code so that you dont have to face error for those specific IP addresses. 

Real-World Use Cases


Lets try to understand why IP geolocation can be very efficient and beneficial for some cases: 

Content Localization: When you have a website or ecommerce business targeting customers worldwide, you can get a better view about customer behavior and understand their needs efficiently. For example, you might want to show specific currency according to the customer's own location or you would want to show / hide product based on the locality. Also you can localize the website language based on from where the request coming from. You can show customized ad to the relevant people connect with the product they are looking for. Most of the modern website are using these techniques to improve their sales and credibility to become more popular and rich. 

Fraud Detection: You can use the geolocation for improving you site security and track fraudulent activities. For example, if you find a user is constantly trying login different countries in a very short amount of time, the system can trace it as a security threat of unusual activity and restrict user from logging in for some time or inform admin with an automated email to take action. 

Traffic Analysis: Based on the user's activity in the website, the business owner and management board can take data driven decisions which is more impactful and beneficial both in business and client end. 

Best Practices for Using IP Geolocation


When integrating IP geolocation into your application, consider the following best practices:

Respect User Privacy: When you are using geolocation for collecting details about user's IP and location, please make sure to inform them about your activity. Add it to your privacy policy or terms and conditions page. You should also provide an option for them to opt out and also make sure your application complies with the data protection regulations, such as GDPR

Use Caching Wisely: As you will have to deal with a large amount of requests and then converting them to IP location details, it might be stressful for system to do so. Make the caching system efficient, so once an IP details is extracted, you can use information from caching for same IP address again. This will keep your system up and running with better performance and user experience. 

Handle Null Values Gracefully: As these are third party packages, there can always be some unexpected or empty results in return for some cases. Make sure you add proper condition, so system can handle those cases and doesnt fall into error. 

Test Across Multiple Environments: Also test in multiple environments like development, staging, production that your code is working perfectly in all scenarios. 

Conclusion


In short, these two packages are very popular choice to get user or IP information for Laravel framework. Though Laravel provides basic access to IP information, you can get more details like country, city, region or coordinates from these powerful packages. 

The stevebauman package provides a extensive way to install it in the project very quickly and a straightforward API. This provides an excellent choice to developers to use it efficiently in the application. However, torann/geoip package offers more control, feature and flexibility like giving options to change data sources or additional customization options. By understanding both the package and their functionalities, you can decide which matches best to your needs and output. 

Respect user privacy by informing them about data collection and taking their concerns to be compliant with the data protection regulations. Install and use caching in effective way so the application performance stays in top notch. 

By applying these conditions, you will ensure a secure and satisfactory output for your application. Thats all for today, let me know your thoughts in the comments below, and also please give a love to this article. Wish you a happy day. 

Comments

Login As User
Word Count: 0