Table of contents

how to get current user location using ip address in laravel

In this post, I'm sharing how to get the current user location using the IP address in Laravel 8. Usually building a project we need to determine where our users came from so that we have their location so that we have an idea about it. Like if we need to scale our server or business in that location because we have many users from there.

 

how to get current user location using ip address in laravel

 

In this example, I'm using stevebauman/location package to make easier our task.

 

Here is the step by step below:

 

I assume that you have basics already about Laravel and you have your local project already.

 

First, we need to install the package. Run the following command below:

composer require stevebauman/location

 

Second, after installing the package. Let's create our controller. Run the following command below:

php artisan make:controller UserLocationController

 

Third, create our route. See below sample:

Route::get('/user-location', 'UserLocationController@index')->name('user.location.index');

 

Then check our controller code below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stevebauman\Location\Facades\Location;

class UserLocationController extends Controller
{
    public function index() 
    {
        // Call this dynamically or use 
        // $_SERVER['REMOTE_ADDR'] but only works in server not in local
        $yourUserIpAddress = '66.102.0.0';

        $location = Location::get($yourUserIpAddress);

        return view('user-location.index', compact('location'));
    }
}

 

As you can see I imported the Location class and we call it to our index() method.

 

Then next let's view it.

 

@extends('layouts.app-master')

@section('content')
    <div class="bg-light p-5 rounded">
        <h1>How To Get Current User Location using IP Address in Laravel 8</h1>
        
        <div class="mt-5">
            <p><b>Country:</b> {{ $location->countryName }}</p>
            <p><b>Country Code:</b> {{ $location->countryCode }}</p>
            <p><b>Region Code:</b> {{ $location->regionCode }}</p>
            <p><b>Region Name:</b> {{ $location->regionName }}</p>
            <p><b>City Name:</b> {{ $location->cityName }}</p>
            <p><b>Zip Code:</b> {{ $location->zipCode }}</p>
            <p><b>Latitude:</b> {{ $location->latitude }}</p>
            <p><b>Longitude:</b> {{ $location->longitude }}</p>
            <p><b>Area Code:</b> {{ $location->areaCode }}</p>
        </div>
    </div>
@endsection

 

That's it you have the basics on how to do it. I hope it helps. For more info about the package, we are using kindly check here.

 

Thank you for reading. Cheers :)