skip to Main Content

Laravel Get User Location Using IP Address

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.

Saroj

I am a web designer and developer part-time blogger. Write something on some free time. Find my every day thought here :)

This Post Has 2 Comments
    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.

Leave a Reply

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

Back To Top