How to Get Location Information with IP Address in Laravel 10

Last Updated on by in Laravel

In this tutorial, we will ascertain how to get location information using ip address in the laravel application using location package.

Also, we will install and configure “stevebauman/location” composer package to get location information of specific IP address in the laravel app.

The stevebauman/location is an excellent library for detecting a users location by their IP Address, and It made retrieving a user’s location information from IP address exorbitantly effortless.

Here is the complete list of location information that we are going to get based on IP address in laravel app with location library:

  • Country name and code
  • Region name and code
  • City name
  • Zipcode
  • ISO code
  • Postal code
  • Latitude and longitude
  • Metro code

Create Laravel Project

Make sure you have composer package installed on your development system. Move to terminal, open a new window and execute command to create or install a new laravel application:

composer create-project laravel/laravel laravel-get-location-information-example --prefer-dist

Make Database Connection

In the second step, you need to append database name, user name and password in .env config file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=databse
DB_USERNAME=root
DB_PASSWORD=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Install Location Package

Now, this is the time to evoke the stevebauman/location package installation; execute a command in the console:

composer require stevebauman/location

Register Location Package

Once the location package is successfully installed then after, you have to register the package classes in providers and aliases arrays:

Add the following code in config/app.php file:

'providers' => [
    ....
    ....
    ....
 
    Stevebauman\Location\LocationServiceProvider::class,
 
],
 
'aliases' => [ 
    ....
    ....
    ....
 
    'Location' => 'Stevebauman\Location\Facades\Location',
 
]

Consequently, you have to publish the location vendor file separately.

Run the following command:

Which provider or tag’s files would you like to publish?

In response to the above question choose following provider from the options list using a number prefix:

Provider: Stevebauman\Location\LocationServiceProvider
php artisan vendor:publish

You can also check on the config/location.php path.

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Driver
    |--------------------------------------------------------------------------
    |
    | The default driver you would like to use for location retrieval.
    |
    */

    'driver' => Stevebauman\Location\Drivers\IpApi::class,

    /*
    |--------------------------------------------------------------------------
    | Driver Fallbacks
    |--------------------------------------------------------------------------
    |
    | The drivers you want to use to retrieve the users location
    | if the above selected driver is unavailable.
    |
    | These will be called upon in order (first to last).
    |
    */

    'fallbacks' => [

        Stevebauman\Location\Drivers\IpInfo::class,

        Stevebauman\Location\Drivers\GeoPlugin::class,

        Stevebauman\Location\Drivers\MaxMind::class,

    ],

    /*
    |--------------------------------------------------------------------------
    | Position
    |--------------------------------------------------------------------------
    |
    | Here you may configure the position instance that is created
    | and returned from the above drivers. The instance you
    | create must extend the built-in Position class.
    |
    */

    'position' => Stevebauman\Location\Position::class,

    /*
    |--------------------------------------------------------------------------
    | MaxMind Configuration
    |--------------------------------------------------------------------------
    |
    | The configuration for the MaxMind driver.
    |
    | If web service is enabled, you must fill in your user ID and license key.
    |
    | If web service is disabled, it will try and retrieve the users location
    | from the MaxMind database file located in the local path below.
    |
    */

    'maxmind' => [

        'web' => [

            'enabled' => false,

            'user_id' => '',

            'license_key' => '',

            'options' => [

                'host' => 'geoip.maxmind.com',

            ],

        ],

        'local' => [

            'path' => database_path('maxmind/GeoLite2-City.mmdb')

        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | IP API Pro Configuration
    |--------------------------------------------------------------------------
    |
    | The configuration for the IP API Pro driver.
    |
    */

    'ip_api' => [

        'token' => env('IP_API_TOKEN'),

    ],

    /*
    |--------------------------------------------------------------------------
    | IPInfo Configuration
    |--------------------------------------------------------------------------
    |
    | The configuration for the IPInfo driver.
    |
    */

    'ipinfo' => [

        'token' => env('IPINFO_TOKEN'),

    ],

    /*
    |--------------------------------------------------------------------------
    | Localhost Testing
    |--------------------------------------------------------------------------
    |
    | If your running your website locally and want to test different
    | IP addresses to see location detection, set 'enabled' to true.
    |
    | The testing IP address is a Google host in the United-States.
    |
    */

    'testing' => [

        'enabled' => env('LOCATION_TESTING', true),

        'ip' => '66.102.0.0',

    ],

];

Generate and Setting Up Controller

Further, you need to generate a controller in this file; we will create the function to handle the request to fetch the location information and pass it on to view:

:

Open and define the following code in app\Http\Controllers\LocationController.php file:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class LocationController extends Controller
{
    public function index(Request $request)
    {
            $userIp = $request->ip();
            $locationData = \Location::get($userIp);
            
            dd($locationData);
    }
}

Build Routes

You need to import LocationController in the routes/web.php file and define a route with the get method to call the index method for showing user location information based on IP address:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LocationController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
*/

Route::get('show-user-location-data', [LocationController::class, 'index']);

Check Location Information

You have to start the laravel project with the artisan serve command:

php artisan serve

Open the following URL to access location information with IP address:

http://127.0.0.1:8000/show-user-location-data

Laravel Get Location Information with IP Address

Summary

This tutorial is over; in the above example, we explained how to access user’s location information (country name, country code, region code, city name, zip code, iso code, postal code, latitude, longitude, metro code, area code) using the IP address in Laravel app equally important stevebauman/location plugin.