How to Get Users Country from Their IP Address in Laravel

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 Install

1. Require the package with composer.

composer require "smalldogs/ip2country"

2. Create and populate the database lookup table.

php artisan migrate --package="smalldogs/ip2country"

3. Add the service to your providers array in app/config/app.php

'providers' => array(
    // [...]

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 = '';
$someonesCountryCode = Ip2Country::get($someonesIpAddress);


By 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.

php artisan config:publish smalldogs/ip2country

Then navigate to app/config/packages/smalldogs/ip2country/config.php.

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

If you don't want anything returned if the IP address is not found, simply set each of these to => null
Small dog web development studio

View All Our Posts

Web application developers in western Washington, creating user centric web solutions for businesses of all shapes and sizes.

Our projects include ecommerce, event organization, user driven web applications and more.

Small Dog Studios, LLC. Small Dog Studios News