Do you want to find out the Geolocation of visitors using Laravel? Using the GeoIP library, you can find out the geolocation of a user by their IP address. In this article, we discuss a library that easily integrates GeoIP in the Laravel application.
There are a few cases where you need to get details about the geographical location of your visitors. These details include latitude, longitude, time zone, country, currency, etc.
One example of using Geolocation is online stores. In your store, you may want to display different prices and currencies based on the country or region of the visitor. Another example is if someone needs to block their websites for a few countries.
That being said, let’s take a look at how to find Geolocation using the IP address in the Laravel.
Installation of Laravel GeoIP Library
For getting started, you need to install the Laravel Geoip library. Install the library using the command:
composer require torann/geoip
Upon library installation, register the service provider with your application. Open
config/app.php and add service providers to the providers array.
'providers' => [ ...... \Torann\GeoIP\GeoIPServiceProvider::class, ]
Next, add the facade in the aliases array.
'aliases' => [ .... 'GeoIP' => \Torann\GeoIP\Facades\GeoIP::class, ];
After the above steps, publish the configuration using the command:
php artisan vendor:publish --provider="Torann\GeoIP\GeoIPServiceProvider" --tag=config
This command publishes a configuration file to
Find Out Geolocation Using IP Address
We are all set to get Geolocation details using an IP address. The library provides a method to which you need to pass the actual IP address. In return, you get the Geolocation information of an IP address.
Place the below code in your application to fetch details of an IP.
$arr_ip = geoip()->getLocation('YOUR_IP_ADDRESS_HERE'); print_r($arr_ip); echo $arr_ip->country; // get a country echo $arr_ip->currency; // get a currency
While using the library, it can be possible you will get the error ‘This cache store does not support tagging’ with BadMethodCallException. If so, just change the below line from
'cache_tags' => ['torann-geoip-location'],
'cache_tags' => ,
Clear the configuration cache using the command:
php artisan config:cache
Now try again to run your code. This time you should get the output.
I hope you got to know how to integrate GeoIP on the Laravel website. Please share your thoughts and suggestions in the comment section below.
- Find Geolocation Using IP Address for Free in PHP
- A Beginner Guide for Laravel Validation
- How to Log Query in Laravel
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.