How to Get Current User Location in Laravel

In this tutorial i am going to show you how to get current location in laravel 6. Sometimes, we may require to get user location. In this tutorial i am going to show you how we can track user ip address and can find user location information from ip address.

For getting user location information i will use stevebauman/location package. Using this package you can get every information of user like country name, region name, state name longitude, latitude, zip code, iso code, postal code etc.

laravel-track-user-location

So let's start. First we have to install stevebauman/location package. So install it by running the following command.

Step 1 : Install package

composer require stevebauman/location

 

Step 2 : Configure Config file

After installing package we have to setup config file. So open config/app.php file and add service provider and alias.

config/app.php

'providers' => [

	....

	Stevebauman\Location\LocationServiceProvider::class,

],

'aliases' => [

	....

	'Location' => 'Stevebauman\Location\Facades\Location',

]

 

Step 3 : Publish Optional Vendor

we have to also make public configuration file by following command, after run this command you will find config/location.php file. So run bellow command:

php artisan vendor:publish

 

Step 4 : Create Route 

Now everything done. We are ready to get user location information in laravel. So create a route like below and check that by visiting following url.

Route::get('details', function () {

	$ip = '50.90.0.1';
    $data = \Location::get($ip);
    dd($data);
   
});

 

Now if you visit the above declared routeurl and you will get the below output You should see the following output.

how-to-track-user-location

Now if you need the country name ? just print like below

Route::get('details', function () {

	$ip = '50.90.0.1';
    $data = \Location::get($ip);
    dd($data->countryName);

});

Then you will get only user country name.

track-user-location-laravel

Now you have to make it dynamic by replacing static ip address. Just use laravel ip helper function to get it. Have a look

request()->ip();

or \Request::ip();

Then you will get user ip adress. Hope this laravel gps tracking tutorial will help you.