Laravel 9 - Get user location
Laravel 9 - Get user location
In this tutorial, we will discuss how to obtain the user's location in Laravel 9. 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 through integrating user location tracking into a Laravel 9 application using the stevebauman/location package. We start by creating a fresh Laravel project and setting up the development environment with Vite. Next, we install the location package, create a dedicated LocationController, and build a Blade view to display the location data. A route is defined to make the page accessible in the browser. Finally, we test the functionality by running the Laravel development server and visiting the location page to ensure the location details are displayed correctly. This step-by-step process allows you to quickly add geolocation features to your Laravel applications. By the end, you’ll have a fully functional system that can dynamically fetch and show user location data, providing a foundation for location-based features or analytics.
Step # 1 : Create a Fresh Laravel 9 Project.
To begin, create a clean Laravel 9 application. If you already have Laravel installed globally, run.
laravel new location
Alternatively, you can use Composer.
composer create-project laravel/laravel --prefer-dist location
This will generate a brand-new Laravel project with all the default directories and files in place. With this fresh setup, you’ll have a stable foundation to start building the front-end and integrating user location functionality, free from any conflicts or leftover configurations from previous projects.
Step # 2 : Access Your Project and Start the Dev Server.
Once your Laravel project is created, open a terminal (like Git Bash) and navigate to the project’s root folder.
cd c:xampp/htdocs/location
Next, install the necessary dependencies and start the Laravel Vite development server to handle front-end assets.
npm install && npm run dev
Consider opening another terminal window or tab, navigate to your project folder there, and use it for running Laravel commands. This way, your Vite dev server can keep running uninterrupted, allowing you to test and develop your application seamlessly.
Step # 3 : Install the Laravel Location Package.
To handle user location functionality, we’ll use the stevebauman/location package, which simplifies retrieving geographic information based on IP addresses. Run the following command in your project directory.
composer require stevebauman/location
This package offers a simple and efficient way to determine a visitor’s location, including details like country, city, latitude, longitude, and more. We’ll leverage it in our controller to dynamically fetch and display the user’s location within the application. It also provides a reliable foundation for building location-based features, analytics, or personalized content based on user geography.
Step # 4 : Publish the Package Configuration (Optional).
If you want to customize the settings of the stevebauman/location package, you can publish its configuration file by running
php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"
This will create a config/location.php file in your project, where you can adjust options like the default driver, IP detection method, or other package-specific settings. This step is optional, but it gives you flexibility to tailor the location detection behavior to your application’s needs.
Step # 5 : Create a Location Controller.
First, generate the controller by running.
php artisan make:controller LocationController
Then, update the controller to fetch and pass location data to a view.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stevebauman\Location\Facades\Location;
class LocationController extends Controller
{
public function index(Request $request)
{
// Define a static IP for testing purposes
$ip = '9.9.9.9'; // Replace with any valid IP to test
$location = Location::get($ip);
// To get the user's IP dynamically, uncomment the lines below
// $ip = $request->ip();
// $location = Location::get($ip);
// Pass the location data to the 'location' view
return view('location', compact('location'));
}
}
This controller retrieves geographic information for a given IP address using the Laravel Location package. It collects details such as country, region, city, latitude, and longitude, making it easy to work with location data in your application. The data is then sent to a view so it can be displayed in a user-friendly format. Using a static IP for testing helps verify that the package is working correctly before using real user IPs.
Step # 6 : Define a Route for User Location.
First, import the LocationController at the top of your routes/web.php file.
use App\Http\Controllers\LocationController;
Then, define a GET route that points to the index method of your controller.
Route::get('/location', [LocationController::class, 'index'])->name('location.show');
With this route in place, visiting http://127.0.0.1:8000/location will trigger the LocationController to fetch the location data and display it in the view.
Step # 7 : Create a Blade View to Display Location.
To show the user location data in the browser, create a view named location.blade.php inside the resources/views directory (resources/views/location.blade.php) and paste the below code in location.blade.php.
<!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 view dynamically displays location details retrieved by the LocationController. If the location data is available, it shows country, region, city, latitude, longitude, and IP address. Otherwise, it displays a friendly message indicating that the data is not available. The layout is simple and clear, making it easy for users to quickly understand their location information. You can also customize this view to match your application’s design or add additional details as needed.
Step # 8 : Test Your User Location Feature.
Now it’s time to see your location functionality in action. Start the Laravel development server by running the following command in your project directory.
php artisan serve
Once the server is running, open your browser and visit: http://127.0.0.1:8000/location. If everything is set up correctly, you should see the location details displayed on the page, including country, region, city, latitude, longitude, and IP address. If the data is not available, a message will indicate that location information could not be retrieved.
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 implemented a user location feature in Laravel 9. From setting up a clean project to creating the controller, defining routes, and designing a Blade view, you now have a functional system that retrieves and displays location data based on IP addresses. This setup provides a solid foundation to enhance your application further, such as integrating location-based services, analytics, or customized content for users based on their location. For more details and advanced options, please refer to the stevebauman/location package documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments