This code snippet will get and save user location (city, country, longitude, latitude and IP) during login process in Laravel.
Install Location package
composer require stevebauman/location
Publish config file
php artisan vendor:publish --provider="StevebaumanLocationLocationServiceProvider"
Create a migration and Add additional fields in Users Table
php artisan make:migration add_locationinfo_to_users_table --table=users
$table->string('userCity')->nullable();
$table->string('userCountry')->nullable();
$table->string('userLongitude')->nullable();
$table->string('userLatitude')->nullable();
$table->string('userIp')->nullable();
Run the migration
Run the migration
Open and Set location config file for localhost testing in config/location.php
'testing' => [
'enabled' => env('LOCATION_TESTING', true),
'ip' => '66.102.0.0',
],
Edit function index in HomeController
public function index(Request $request)
{
$curuser = Auth()->user()->id;
$currentUserInfo = Location::get();
$updLocation = User::where('id','=',$curuser)->first();
$updLocation->userIP = $currentUserInfo->ip;
$updLocation->userCity = $currentUserInfo->cityName;
$updLocation->userCountry = $currentUserInfo->countryName;
$updLocation->userLongitude = $currentUserInfo->longitude;
$updLocation->userLatitude = $currentUserInfo->latitude;
$updLocation->save();
return view('home');
}