Get User Geographical Location in Laravel

Published on June 19, 2020 57 sec read

In this short article, we’re going to learn how to get user location in Laravel. Let’s get started:

Table of Contents

  1. Install Package
  2. Publish the Configurations
  3. Get Location

Install Package

We’ll use laravel-geoip package. Install the package using this command:

composer require torann/geoip

If you are using Laravel 5.4 or older version, you need to register the service provider with the application. Open up config/app.php and find the providers key.

'providers' => [
    ......
    \Torann\GeoIP\GeoIPServiceProvider::class,
]

This package also comes with an optional facade, which provides an easy way to call the the class. Open up config/app.php and find the aliases key.

'aliases' => [
    ......
    'GeoIP' => \Torann\GeoIP\Facades\GeoIP::class,
];

Publish the Configurations

Run this on the command line from the root of your project:

php artisan vendor:publish --provider="Torann\GeoIP\GeoIPServiceProvider" --tag=config

A configuration file will be publish to config/geoip.php. Open the config file and replace:

'cache_tags' => ['torann-geoip-location'],

With:

'cache_tags' => [],

Get Location

Simply use this helper method to get the user location:

$location = geoip("IP_ADDRESS");
dd($location);

Get current user location:

$location = geoip(request()->ip());
dd($location);

Here’s the example location object:

Torann\GeoIP\Location {#323 ▼
    #attributes: array:14 [▼
    "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"
    "currency" => "USD"
    "default" => true
    "cached" => false
  ]
}

Read this doc to know more about this package.

That’s all. Thank you. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *