How to Get Current User Location in Laravel

In this example i will show how to get current user location in laravel. some time you need to get user location such as client ip, country name, country code, state code, state name, city name, longitude, latitude, zip code.

I will explain step by step get current user location in laravel. In this example i get first current user ip address and after get current user location.

In this example i will use laravel stevebauman/location package, Using this package to get current user many information in laravel.

Step 1 : Install package

In this step we will install stevebauman/Location package in laravel using the following command.
composer require stevebauman/Location

Step 2 : Configure Config file

After install package you can open the config/app.php file and add service provider and alias.
'providers' => [
    Stevebauman\Location\LocationServiceProvider::class,
],
'aliases' => [
    'Location' => 'Stevebauman\Location\Facades\Location',
]

After setup the config file to publish the configuration file by just following command.

php artisan vendor:publish
Step 3 : Create Controller

In this step we will create controller on this path app\Http\Controllers\UserController.php.

Read Also :  Target Class Does Not Exist in Laravel 8
<?php
namespace 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 4 : Create Route

use App\Http\Controllers\UserController;

Route::get('ip_details', [UserController::class, 'ip_details'])->name('ip_details'

Step 5 : Create Blade File

In this step we will create a blade file in details.blade.php and add following html code.

Read Also :  Laravel Left Join Query Example
<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</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>

I hope you understand of laravel get current user location and it can help you…

Read Also :  Laravel Arr only() function Example