Laravel get user location using IP address

Laravel how can we get the user location details using IP address. Sometimes we need to get the user location detail and address of the site visitors. We can get the user location detail from the user IP address using Laravel.

Let’s see how we can get the user location from the user IP address.

We used “stevebauman/location” laravel package for getting the user location address from IP address.

Let’s first installed “stevebauman/location” package to laravel. add below package to your “composer.json” file.

"stevebauman/location": "2.0.*"

Then run composer update command for download and install the package to Laravel.

After installing the package let’s register the location providers and facades to Laravel. So let’s, open the “config/app.php’ file and add below providers and facades.

Stevebauman\Location\LocationServiceProvider::class,

Add the alias in your “config/app.php” file.

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

Now let’s, publish configuration file using below command.

php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"

The package is ready for used. let’s get the current user location detail.

Route::get('/get/ipLocation',function(){

    $ipAddress = $_SERVER['REMOTE_ADDR'];
    //72.229.28.185

    $position = \Location::get( $ipAddress );

    echo '<pre>';
    print_r($position);
    exit;

});

We create the route for getting the user address location. The output of the above code like

Stevebauman\Location\Position Object
(
    [countryName] => 
    [countryCode] => US
    [regionCode] => 
    [regionName] => Florida
    [cityName] => Miami
    [zipCode] => 33110
    [isoCode] => 
    [postalCode] => 
    [latitude] => 25.8469
    [longitude] => -80.2083
    [metroCode] => 
    [areaCode] => 
    [driver] => Stevebauman\Location\Drivers\IpInfo
)

This package is very useful for getting the user location details.

If you face any issue with getting the user location write the comment below.

2 thoughts on “Laravel get user location using IP address”

    1. Hello Naveed,
      Thanks for the comment.
      You can get the country and city name like
      $country_name = $position->countryName;
      $city_name = $position->cityName;
      Let me know if you have any other confusion.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s