In this tutorial, we are going to learn how to get location information in Laravel using Ip.

Prerequisites

  • Laravel
  • To Continue with this tutorial, you should have installed Laravel 8 in your pc. If you are still not installed Laravel in your machine you can configure it from here.

    Setting up the Project

    First you need to create a new laravel project by running below command in your terminal
    1
    composer create-project laravel/laravel laravel-get-location-information

    Then navigate to your project directory by using below command in your terminal

    1
    cd laravel-get-location-information

    Install stevebauman/location Package

    There are many other other packages aprt from stevebauman/location to get location from IP in Laravel but in this tutorial we use stevebauman/location. To install this package open ypour terminal and run below command:
    1
    composer require stevebauman/location

    Add Service Provider And Aliase

    After package installation we need to add service provider and aliase in `config/app.php`.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    'providers' => [

    Stevebauman\Location\LocationServiceProvider::class,
    ],

    'aliases' => [

    'Location' => 'Stevebauman\Location\Facades\Location',
    ],

    Create Location Controller

    Now create controller on this path `app\Http\Controllers\LocationController.php` and add below command.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <?php

    namespace App\Http\Controllers;

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

    class LocationController extends Controller
    {
    public function index(Request $request)
    {
    $ip = '103.239.157.189'; //For static IP address get
    //$ip = request()->ip(); //Dynamic IP address get
    $ip = request()->header('X-Forwarded-For');
    $data = \Location::get($ip);
    dd($data);
    }
    }

    Create Route

    In your `routes/web.php` add below code:
    1
    2
    3
    4
    5
    6
    <?php

    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\LocationController;

    Route::get('location', [LocationController::class, 'index']);

    Check Location Information

    Now we have finished with our configuration part. To get location information, run below command in your terminal:
    1
    php artisan serve

    After that visit http://127.0.0.1:8000/location

    Conclusion

    In this tutorial, we implemented get location details using IP in Laravel. If you have any issue regarding this tutorial, mention your issue in comment section or reach me through my E-mail.You can obtain complete source code for this tutorial from this GitHub repository.

    Happy Coding