How Get User Exact Location Using IP Address in Laravel 11 |
How Get User Exact Location Using IP Address in Laravel 11 |

How Get User Exact Location Using IP Address in Laravel 11

In the digital age, understanding your users’ locations can greatly enhance the user experience of your web application. Laravel, a popular PHP framework, provides convenient ways to fetch user location using their IP address. In this tutorial, we’ll walk through the process of fetching user location using IP address in Laravel 11.

Step 1: Install Required Packages

To begin, we need to install a package that helps us to determine the location based on the user’s IP address. We’ll use the “stevebauman/location” package for this purpose.

composer require stevebauman/location

Step 2: Configure the Package

Once the package is installed, we need to configure it in our Laravel application. Open the config/app.php file and add the following line to the ‘providers’ array:


Next, publish the configuration file using the following artisan command:

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

This command will create a config/location.php file where you can configure the package settings.

Step 3: Fetch User Location

Now, let’s implement the logic to fetch the user’s location based on their IP address. We’ll create a new controller method for this purpose.

use Stevebauman\Location\Facades\Location;

public function getUserLocation()
$ipAddress = request()->ip();
$location = Location::get($ipAddress);

return $location;

In this method, we first fetch the user’s IP address using Laravel’s request()->ip() method. Then, we pass this IP address to the Location::get() method provided by the package to get the user’s location information.

Step 4:

Display User LocationFinally, let’s display the user’s location information in our view. We’ll update the view file to show the user’s city, region, country, and postal code.

<!DOCTYPE html>
<title>User Location</title>
<h1>User Location Information</h1>
<p>City: {{ $location['city'] }}</p>
<p>Region: {{ $location['region'] }}</p>
<p>Country: {{ $location['country'] }}</p>
<p>Postal Code: {{ $location['postal'] }}</p>

Step 5: Route and Access

To access the user’s location information, we need to define a route that points to our controller method and returns the view.

Route::get('/user/location', 'UserController@getUserLocation');

Now, when you navigate to /user/location in your browser, you should see the user’s location information displayed on the screen.

That’s it! You’ve successfully implemented fetching user location using their IP address in Laravel 11. This information can be useful for personalizing user experiences or performing location-based actions in your application.