Laravel 10 - Get user location

Touseef Afridi
03 Sep 24

Laravel 10 - Get user location

In this tutorial, we will discuss how to obtain the user's location in Laravel 10. Obtaining the user's location can help personalize content and services, such as displaying relevant local information or ads. It also enhances security by detecting and preventing fraudulent activities based on geographic location.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

In this guide, we walk you through how to fetch and display a user’s location in a Laravel 10 application using the stevebauman/location package. We start by setting up a fresh Laravel project and running the Vite development server. Then, we install the location package, publish its configuration, and create a controller to retrieve geolocation data based on IP addresses. After defining a route, we build a simple Blade view to display the country, city, region, latitude, longitude, and IP address. By the end, when you visit /location, you'll see real-time user location details fetched dynamically, making it a powerful feature for personalization, analytics, or content targeting.

Step # 1 : Start with a Fresh Laravel 10 Project (or Use Your Existing One).

To begin, make sure you have a Laravel 10 project ready. You can either use an existing application or create a new one to work in a clean and isolated environment. Starting fresh is often ideal when testing new features to avoid conflicts with old code or settings. If you have the Laravel installer globally set up, run.
laravel new location
Or, if you prefer Composer.
composer create-project laravel/laravel --prefer-dist location
This will generate a new Laravel application inside a folder named location, giving you a clean foundation to start building your feature without any clutter from previous development work.

Step # 2 : Access the Project and Start the Vite Server.

Open your terminal (e.g., Git Bash) and navigate to the root directory of your Laravel project. For example.
cd c:xampp/htdocs/location
Next, install the front-end dependencies and start the Vite development server to handle your CSS and JavaScript assets.
npm install && npm run dev
Keep this terminal window open, as Vite needs to keep running in the background. Then, open a new terminal tab or window, return to the same project folder, and use it to run Laravel-specific commands as you move forward.

Step # 3 : Install the Laravel Location Package.

To retrieve the user's geolocation based on their IP address, you'll need to install the stevebauman/location package. Run the following Composer command in your terminal.
composer require stevebauman/location
This package makes it easy to fetch location details such as the user's country, region, city, postal code, latitude, longitude, and even timezone, just from their IP address. It leverages external geolocation services behind the scenes, like ip-api or ipinfo.io, to provide accurate data. Once installed, you’ll be able to integrate real-time location detection into your Laravel application, which can be useful for analytics, localization, content customization, or even access restrictions based on geography.

Step # 4 : Publish the Configuration File.

To customize how the Laravel Location package behaves, you can publish its configuration file using the following Artisan command.
php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"
This command will generate a location.php file inside the config directory. This file contains customizable settings such as the default geolocation driver, API timeouts, fallback behaviors, and service-specific configurations. It allows you to fine-tune how the package fetches and handles location data in your Laravel application.

Step # 5 : Create a LocationController.

Run the following Artisan command to generate a controller that will handle location-based logic.
php artisan make:controller LocationController
Once created, open the generated LocationController.php file and update it with the following code.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stevebauman\Location\Facades\Location;
class LocationController extends Controller
{
    public function index(Request $request)
    {
        // Use a static IP address for testing purposes.
        $ip = '9.9.9.9'; // You can replace this with any public IP to test different locations.
        $location = Location::get($ip);
        // For real usage, uncomment the lines below to fetch the user's actual IP dynamically:
        // $ip = $request->ip();
        // $location = Location::get($ip);
        return view('location', compact('location'));
    }
}
This controller fetches location information using the IP address (either static for testing or dynamic in production) and passes it to a Blade view named location. You’ll use this data to display the user’s country, city, region, and more.

Step # 6 : Create a Route.

To connect the controller to the browser, define a route that points to the index method of your LocationController. Open your routes/web.php file and add the following.
use App\Http\Controllers\LocationController;
Route::get('/location', [LocationController::class, 'index'])->name('location.show');
This registers a /location route in your application. When a user visits this URL, Laravel will invoke the index method from the LocationController, retrieve the location data, and pass it to the view. The route is also named location.show, making it easier to reference in views or redirects later.

Step # 7 : Create a View to Display Location Data.

Now that your controller is ready and the route is set up, let’s build a Blade view to display the user’s location details in the browser. Create a view named location.blade.php and paste the following code.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Location</title>
</head>
<body>
    <h1>User Location</h1>
    @if($location)
        <p><strong>Country:</strong> {{ $location->countryName }}</p>
        <p><strong>Region:</strong> {{ $location->regionName }}</p>
        <p><strong>City:</strong> {{ $location->cityName }}</p>
        <p><strong>Latitude:</strong> {{ $location->latitude }}</p>
        <p><strong>Longitude:</strong> {{ $location->longitude }}</p>
        <p><strong>IP Address:</strong> {{ $location->ip }}</p>
    @else
        <p>Location data is not available.</p>
    @endif
</body>
</html>
This simple Blade template checks if location data is available. If it is, it neatly displays the country, city, region, coordinates, and IP address. If not, it shows a fallback message. You can style or expand this layout later to match your application’s theme.

Step # 8 : It's Time to Test.

Now that everything is set up, let’s run the Laravel server and verify that the location detection is working correctly. Start the Laravel development server.
php artisan serve
Visit the following URL in your browser.
http://127.0.0.1:8000/location
If everything is working as expected, you should see the user’s location details displayed on the screen, similar to.
User Location
Country: Some Country
Region: Some Region
City: Some City
Latitude: Some Latitude
Longitude: Some Longitude
IP Address: IP

Conclusion

By following this step-by-step guide, you’ve successfully integrated IP-based location tracking into your Laravel 10 application using the stevebauman/location package. Starting from a fresh setup, you configured the environment, installed the necessary package, created a controller, and built a clean view to display location data. This feature allows your application to retrieve and show useful geographic information such as country, region, city, and coordinates based on the user’s IP address. Whether you're building personalized experiences, gathering analytics, or applying regional content rules, this setup provides a solid foundation to work with real-time location data in Laravel.
For more details, please refer to the stevebauman/location package documentation.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering