stevebauman/location composer package allows users to get country name, country code, area code, area name, city name, zip code, latitude and longitude, address using IP address in Laravel 11 application.
Let’s start to get current user location using ip address:
Step 1: Install stevebauman/location
Run the following command to install stevebauman/location composer package:
composer require stevebauman/location
Step 2: Define Routes
Edit .env file and define routes to handle user location via ip address:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::get('user', [UserController::class, 'index']);
Step 3: Create Controller
Run the following command to create a controller file:
php artisan make:UserController
Add the following code in userController.php file to get current user location using ip address:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Stevebauman\Location\Facades\Location;
use Illuminate\View\View;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request): View
{
$ip = $request->ip() // Static IP: $ip = '162.159.24.227';
$currentUserInfo = Location::get($ip);
return view('location', compact('currentUserInfo'));
}
}
Step 4: Create Blade File
Create blade view file location.blade.php file in resources/views directory to display current user location:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Laravel 11 Get Current User Location - ItcodStuff.com</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="card mt-5">
<h3 class="card-header p-3">Laravel 11 Get Current User Location - ItcodStuff.com</h3>
<div class="card-body">
@if($currentUserInfo)
<p><strong>IP:</strong> {{ $currentUserInfo->ip }}</p>
<p><strong>Country Name:</strong> {{ $currentUserInfo->countryName }}</p>
<p><strong>Country Code:</strong> {{ $currentUserInfo->countryCode }}</p>
<p><strong>Region Code:</strong> {{ $currentUserInfo->regionCode }}</p>
<p><strong>Region Name:</strong> {{ $currentUserInfo->regionName }}</p>
<p><strong>City Name:</strong> {{ $currentUserInfo->cityName }}</p>
<p><strong>Zip Code:</strong> {{ $currentUserInfo->zipCode }}</p>
<p><strong>Latitude:</strong> {{ $currentUserInfo->latitude }}</p>
<p><strong>Longitude:</strong> {{ $currentUserInfo->longitude }}</p>
@endif
</div>
</div>
</div>
</body>
</html>
Step 5: Test Application
Run the following command to start laravel application development server:
php artisan serve
And type the following URL in browser to view the app output:
http://localhost:8000/user