Table of Contents
In this tutorial, we will learn how to get country, city name, and address using IP address in Laravel application. We will use stevebauman/location composer package to get the current user location in the Laravel app. We will retrieve the country name, country code, Region code, Region name, city name, zip code, Latitude, and Longitude from the IP Address.
- Basic knowledge of Laravel.
- A Laravel 10 application up and running.
- Composer installed on your machine.
Step 1: Install Laravel:
The first step is to create a new Laravel application. Open your terminal or command prompt and run the following command:
composer create-project laravel/laravel blog
Step 2: Install stevebauman/location Package:
After creating the Laravel application, you need to install the stevebauman/location package using the following command:
composer require stevebauman/location
Step 3: Create Route:
In this step, we need to create some routes for the UserController. Open
routes/web.php file and add the following code:
use App\Http\Controllers\UserController; Route::get('view-user', [UserController::class, 'index']);
Step 4: Create Controller:
Next, we need to create a UserController and add the following code in the
In the above code, we are getting the IP address of the user and then getting the location details using the
Location facade from the stevebauman/location package.
Step 5: Create Blade Files:
In this step, we need to create a blade file for the user. Create a
resources/views/user.blade.php file and add the following code:
In the above code, we are displaying the user’s IP address, country name, country code, region code, region name, city name, zip code, latitude and longitude.
Step 6: Test the App
php artisan serve
Now, go to your web browser and type the URL “http://localhost:8001/view-user” to view the output of your app. You should be able to see the current user location displayed on the page, including the IP address, country name, country code, region code, region name, city name, zip code, latitude, and longitude.
Congratulations! You have successfully learned how to get country, city name, and address using an IP address in a Laravel application. This tutorial has shown you how to install the stevebauman/location composer package, create routes and a controller, and create a blade file to display the current user location. You can now use this knowledge to implement location-based features in your Laravel applications.