• Stars
    star
    1,104
  • Rank 42,038 (Top 0.9 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 10 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Detect a users location by their IP Address.

Location

Retrieve a visitor's location from their IP address using various services.

Requirements

  • PHP >= 8.1
  • Laravel >= 8.0

Installation

Install location using composer require:

composer require stevebauman/location

Publish the configuration file (this will create a location.php file inside the config directory):

php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"

Usage

Retrieve a client's location

use Stevebauman\Location\Facades\Location;

if ($position = Location::get()) {
    // Successfully retrieved position.
    echo $position->countryName;
} else {
    // Failed retrieving position.
}

Important:

  • This method retrieves the user's IP address via request()->ip().
  • In the default configuration, testing.enabled is active, the returned IP address is in the USA. Disable it to get the client's real IP address.

Retrieve the location of a specific IP address

$position = Location::get('192.168.1.1');

Drivers

Available Drivers

Available drivers:

Setting up MaxMind with a self-hosted database (optional)

We encourage setting up MaxMind as a fallback driver using a local database, as it allows you to bypass any throttling that could occur from using external web services.

To set up MaxMind to retrieve the user's location from your own server, you must:

  1. Create a maxmind account and sign in
  2. Click "Manage License Keys" from the profile menu dropdown
  3. Generate a new license key
  4. Copy the license key and save it into your .env file using the MAXMIND_LICENSE_KEY key
  5. Run php artisan location:update to download the latest .mmdb file into your database/maxmind directory
  6. That's it, you're all set!

Note: Keep in mind, you'll need to update this file by running location:update on a regular basis to retrieve the most current information from your visitors.

Fallback Drivers

In the config file, you can specify as many fallback drivers as you wish. It is recommended to configure the MaxMind driver with the local database .mmdb file (mentioned above), so you are alwaysretrieving some generic location information from the visitor.

If an exception occurs trying to grab a driver (such as a 400/500 error if the providers API changes), it will automatically use the next driver in line.

Creating your own drivers

To create your own driver, simply create a class in your application, and extend the abstract Driver:

namespace App\Location\Drivers;

use Illuminate\Support\Fluent;
use Illuminate\Support\Facades\Http;
use Stevebauman\Location\Position;
use Stevebauman\Location\Request;
use Stevebauman\Location\Drivers\Driver;

class MyDriver extends Driver
{    
    protected function process(Request $request): Fluent
    {
         $response = Http::get("https://driver-url.com", ['ip' => $request->getIp()]);
         
         return new Fluent($response->json());
    }

    protected function hydrate(Position $position, Fluent $location): Position
    {
        $position->countryCode = $location->country_code;

        return $position;
    }
}

Then, insert your driver class name into the configuration file:

// config/location.php

'driver' => App\Location\Drivers\MyDriver::class,

Upgrading from v6

In version 7, the codebase has been updated with strict PHP types, updated PHP and Laravel version requirements, an updated Driver structure, as well as a small configuration addition.

Configuration

In version 7, location drivers can now implement an Updatable interface that allows them to be updated using the location:update command. Currently, only the MaxMind driver supports this.

To update your configuration file to be able to download the latest MaxMind database file automatically, insert the below url configuration option in your config/location.php file:

// config/location.php

return [
    'maxmind' => [
        // ...
        
        'local' => [
            // ...
            
+            'url' => sprintf('https://download.maxmind.com/app/geoip_download?edition_id=GeoLite2-City&license_key=%s&suffix=tar.gz', env('MAXMIND_LICENSE_KEY')),
        ],
    ],
];

Once done, you may execute the below artisan command to download the latest .mmdb file:

php artisan location:update

Drivers

In version 7, the codebase has been updated with strict PHP types, updated PHP and Laravel version requirements, and an updated Driver structure.

If you have created your own custom driver implementation, you must update it to use the base Driver or HttpDriver class.

If you're fetching a location using an HTTP service, it may be useful to extend the HttpDriver to reduce the code you need to write:

namespace App\Location\Drivers;

use Illuminate\Support\Fluent;
use Stevebauman\Location\Position;
- use Stevebauman\Location\Drivers\Driver;
+ use Stevebauman\Location\Drivers\HttpDriver;

- class MyDriver extends Driver
+ class MyDriver extends HttpDriver
{
-    public function url($ip)
+    public function url(string $ip): string;
    {
        return "http://driver-url.com?ip=$ip";
    }
    
-    protected function process($ip)
-    {
-        return rescue(function () use ($ip) {
-            $response = json_decode(file_get_contents($this->url($ip)), true);
-            
-            return new Fluent($response);
-        }, $rescue = false);
-    }

-    protected function hydrate(Position $position, Fluent $location)
+    protected function hydrate(Position $position, Fluent $location): Position;
    {
        $position->countryCode = $location->country_code;

        return $position;
    }
}

Versioning

Location is versioned under the Semantic Versioning guidelines as much as possible.

Releases will be numbered with the following format:

<major>.<minor>.<patch>

And constructed with the following guidelines:

  • Breaking backward compatibility bumps the major and resets the minor and patch.
  • New additions without breaking backward compatibility bumps the minor and resets the patch.
  • Bug fixes and misc changes bumps the patch.

Minor versions are not maintained individually, and you're encouraged to upgrade through to the next minor version.

Major versions are maintained individually through separate branches.

More Repositories

1

showcode

Create beautiful images of code.
Vue
456
star
2

purify

A Laravel wrapper for HTMLPurifier by ezyang
PHP
446
star
3

hypertext

A PHP HTML to pure text transformer.
PHP
148
star
4

unfinalize

Remove "final" keywords from classes and methods in vendor packages.
PHP
135
star
5

curlwind

Generate Tailwind utility stylesheets on demand.
CSS
128
star
6

autodoc-facades

Auto-generate PHP doc annotations for Laravel facades
PHP
89
star
7

laravel-husk

A thin and light scaffolded Laravel Dusk environment.
PHP
88
star
8

translation

An easy database driven automatic translator for Laravel 5
PHP
75
star
9

eloquent-table

An HTML table generator for laravel collections
PHP
46
star
10

github-summarizer

A PHP GitHub summarizer using Chat GPT.
PHP
43
star
11

revision

Revisions for Eloquent Models
PHP
39
star
12

maintenance

A Preventative Maintenance Application (CMMS) for Laravel
PHP
37
star
13

log-reader

An easy log reader for Laravel 5
PHP
23
star
14

wmi

A package for WMI manipulation using PHP and COM.
PHP
10
star
15

calendar-helper

A Laravel calendar implementation with Google Calendar
PHP
8
star
16

helpdesk

An IT Helpdesk for managing issues and other related information.
PHP
6
star
17

maintenance-app

The Maintenance Application
JavaScript
6
star
18

pdf

A Dompdf Wrapper for Laravel.
PHP
5
star
19

platform-logs

A cartalyst's platform log manager
PHP
4
star
20

profilepicture-cli

Download all of your 4K images from https://ProfilePicture.ai automatically
PHP
4
star
21

laravel-husk-gridsome

PHP
3
star
22

platform-localization

A localization manager for cartalyst's platform
PHP
3
star
23

laravel-husk-nuxt

A Laravel Husk example using Nuxrt
PHP
3
star
24

Corp

An AdLDAP Helper Package for Larvel 4/5
PHP
2
star
25

administration

An administration backend scaffolding package for Laravel.
PHP
2
star
26

active

An active HTML class helper that echo's strings based on the current route.
PHP
2
star
27

showcode-api-docs

Showcode API docs
JavaScript
1
star
28

viewer

A presenter-like package but used for attaching modular views on a retrieved eloquent record
PHP
1
star
29

WinSchedule

Actual PHP task scheduling in Windows using COM.
PHP
1
star
30

stevebauman-blog

A repository for hosting blog comments for stevebauman.ca
1
star
31

flash

Sweet Alert flash notifications in Laravel.
PHP
1
star
32

WinPerm

A Windows File / Folder Permission Parser in PHP.
PHP
1
star