How to get current user location with Laravel
In this tutorial, we will discuss How to get the current user location with Laravel. Many times our client is required to find the current location of users for any purpose Like which location to user login.
So I am using stevebauman/location
Laravel package. stevebauman/location
get much information about the utilizer like postal code, zip code, country denomination, latitude, iso code, region denomination, state name longitude, etc.
Let’s start to get the current user location with Laravel step by step:
Install Laravel
Type the below command in the terminal to create new project in your system laravel/laravel
.
composer create-project --prefer-dist laravel/laravel user_location
Install stevebauman/location package
Now the installation of the project you need to install stevebauman/location
Package.
composer require stevebauman/location
Add Service Provider And Alises
After successfully package installation we need to add the service provider and aliases.
#config/app.php 'providers' => [ ... Stevebauman\Location\LocationServiceProvider::class, ], 'aliases' => [ ... 'Location' => 'Stevebauman\Location\Facades\Location', ],
Create Controller
Now we create a controller on this path app\Http\Controllers\
.
php artisan make:controller UsersController
#app\Http\Controllers\UsersController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UsersController extends Controller { public function get_details() { // $ip = request()->ip(); // Dynamic IP address $ip = '162.241.148.160'; // Static IP address $datas = \Location::get($ip); return view('display',compact('datas')); } }
Add Route
We need to add a route for the details view file calls.
# routes/web.php <?php // Laravel 7 Route::get('ip_details', 'UsersController@get_details'); // Laravel 8 Route::get('ip_details', [App\Http\Controllers\UsersController::class, 'get_details']);
Create Blade File
Now, create a display.blade.php file to get the current user location details.
#resources\views\display.blade.php and put below html code. <html> <head> <title>How to get current user location with Laravel</title> </head> <body style="text-align: center; font-family: -webkit-pictograph;"> <h1>How to get current user location with Laravel - Devnote.in</h1> <div style="border:1px solid #e2e2e2; margin: 0 300px;"> <h4>IP: {{ $datas->ip }}</h4> <h4>Country Name: {{ $datas->countryName }}</h4> <h4>Country Code: {{ $datas->countryCode }}</h4> <h4>Region Code: {{ $datas->regionCode }}</h4> <h4>Region Name: {{ $datas->regionName }}</h4> <h4>City Name: {{ $datas->cityName }}</h4> <h4>Zipcode: {{ $datas->zipCode }}</h4> <h4>Latitude: {{ $datas->latitude }}</h4> <h4>Longitude: {{ $datas->longitude }}</h4> </div> </body> </html>
Now open a browser and enter http://127.0.0.1:8000/ip_details
.