Do you want to find out the Geolocation of visitors using Laravel? Using the Laravel GeoIP library, you can get the geolocation of a user by their IP address. In this article, we discuss this library that can be easily integrated into the Laravel application to find the GeoIP.
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.
The online store is probably an example where you require to get Geolocation. 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.
Install and Configure 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' => [ ...... \Torann\GeoIP\GeoIPServiceProvider::class, ],
Next, add the Facade to the
'aliases' => Facade::defaultAliases()->merge([ ... 'GeoIP' => \Torann\GeoIP\Facades\GeoIP::class, ])->toArray(),
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
The library provides a method where 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 address.
$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
You may get the IP address of a user using the
getClientIP() method provided by this library.
$arr_ip = geoip()->getLocation(geoip()->getClientIP());
While using the library, it can be possible you get the error ‘This cache store does not support tagging’ with BadMethodCallException. If it occurs, just change the below line from the
'cache_tags' => ['torann-geoip-location'],
'cache_tags' => ,
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.