How To Get Current User Location In Laravel
- In this Example I will show you how to get current user location in laravel, Many times we required to find current location of users for many purpose.
- So, here I am using stevebauman/location laravel package, Using this package you can get many information of utilize like postal code, zip code, region denomination, state name longitude, country denomination, latitude, ISO code, etc.
- So,let’s start and follow below step one by one.
Step 1 : Install Laravel
Type the following command in terminal for create new project in your system.
composer create-project — prefer-dist laravel/laravel get_location
Step 2 : Install stevebauman/location Package In Your Application
After installation of project you need to install stevebauman/location Package
composer require stevebauman/location
Step 3 : Add Service Provider And Aliase
After package installation we need to add service provider and aliase in config/app.php.
‘providers’ => [
Stevebauman\Location\LocationServiceProvider::class,
],‘aliases’ => [
‘Location’ => ‘Stevebauman\Location\Facades\Location’,
],
Step 4 : Create Controller
Now create controller on this path app\Http\Controllers\UserController.php and add below command.
<?phpnamespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;class UserController extends Controller
{
public function ip_details()
{
$ip = ‘103.239.147.187’; //For static IP address get
//$ip = request()->ip(); //Dynamic IP address get
$data = \Location::get($ip);
return view(‘details’,compact(‘data’));
}
}
Step 5 : Add Route
We need to add route for details view file.
<?phpuse Illuminate\Support\Facades\Route;Route::get(‘ip_details’, ‘UserController@ip_details’);
Step 6 : Create Blade File
Now, create details.blade.php file for get current user location details in this path resources\views\details.blade.php and add below html code.
<html>
<head>
<title>How to get current user location in laravel</title>
</head>
<body style=”text-align: center;”>
<h1> How to get current user location in laravel — websolutionstuff.com</h1>
<div style=”border:1px solid black; margin-left: 300px; margin-right: 300px;”>
<h3>IP: {{ $data->ip }}</h3>
<h3>Country Name: {{ $data->countryName }}</h3>
<h3>Country Code: {{ $data->countryCode }}</h3>
<h3>Region Code: {{ $data->regionCode }}</h3>
<h3>Region Name: {{ $data->regionName }}</h3>
<h3>City Name: {{ $data->cityName }}</h3>
<h3>Zipcode: {{ $data->zipCode }}</h3>
<h3>Latitude: {{ $data->latitude }}</h3>
<h3>Longitude: {{ $data->longitude }}</h3>
</div>
</body>
</html>
So, finally we are done with our code we can get below output.