How to get Current User Location in Laravel 7

  1191 views   6 months ago Laravel

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

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

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.

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.

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();

i hope you like this.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles