Use Laravel GeoIP to Determine Users’ Geographical Location
Published on by Paul Redmond
I recently needed a geographical check of users to determine default locales and currencies of users. The torann/geoip package by Daniel Stainback fit the bill nicely to provide GeoIP for Laravel 5 applications.
The Laravel GeoIP package supports a few services, including ip-api.com by default, a downloadable Maxmind Database, and the Maxmind API. You can also add a custom service easily through the configuration.
The basic usage of this package is calling the geoip()
helper, optionally passing an IP address. The following is an example location object that is returned based on IP location:
\Torann\GeoIP\Location { #attributes:array [ 'ip' => '232.223.11.11', 'iso_code' => 'US', 'country' => 'United States', 'city' => 'New Haven', 'state' => 'CT', 'state_name' => 'Connecticut', 'postal_code' => '06510', 'lat' => 41.28, 'lon' => -72.88, 'timezone' => 'America/New_York', 'continent' => 'NA', 'currency' => 'USD', 'default' => false, ]}
As you can see, the Location object has some geo-specific data that is helpful in determining the currency of the user, his or her timezone, and country ISO code.
A configurable fallback location is also available in case the location is not found, and the default
parameter will be set to true
. You can override the default configuration, which looks like this:
'default_location' => [ 'ip' => '127.0.0.0', 'iso_code' => 'US', 'country' => 'United States', 'city' => 'New Haven', 'state' => 'CT', 'state_name' => 'Connecticut', 'postal_code' => '06510', 'lat' => 41.31, 'lon' => -72.92, 'timezone' => 'America/New_York', 'continent' => 'NA', 'default' => true, 'currency' => 'USD',],
Check out the package source code on the official GitHub repository, and the documentation to help you get started.