We searched for an easy, fast, way to lookup get a users general location (at least country) for our Laravel app. We couldn't find anything, so we created one.
Ip2Country creates a database table to do the IP lookups locally, so there is no risk waiting for an API response when your user is waiting for their page to load.
Ip2Country currently only supports geo-location lookup of IPv4 addresses, but support for IPv6 is planned.
Here is how to quickly get up and running with user location lookup in Laravel:
See the source on GitHub: smalldogs/ip2country
How to Install1. Require the package with composer.
2. Create and populate the database lookup table.
composer require "smalldogs/ip2country"
3. Add the service to your providers array in
php artisan migrate --package="smalldogs/ip2country"
'providers' => array( // [...] 'Smalldogs\Ip2Country\Ip2CountryServiceProvider', );
How to Use
// Returns the 2 letter country code for the user, eg: 'US' $myCountryCode = Ip2Country::get(); // Returns the full name of the country, eg: 'United States' $myCountryName = Ip2Country::getFull(); // Get the country for someone other than user on the page $someonesIpAddress = '192.168.0.1'; $someonesCountryCode = Ip2Country::get($someonesIpAddress);
ConfigurationBy default, if the IP address is not found in the lookup table, it will return 'US' as a country code, and 'United States' as a country name. You can customize this in the config.
Then navigate to
php artisan config:publish smalldogs/ip2country
If you don't want anything returned if the IP address is not found, simply set each of these to
return array( // If IP address is not found, what country is returned 'default_country_code' => 'US', 'default_country_name' => 'United States', // Since our data will change, at most, once a month. Cache the Ip lookup for a day // Default: 1 day. Set to 0 or null to disable. 'cache_results' => 60 * 24 );