stevebauman/location

repository·master·Indexed 23 days ago

https://github.com/stevebauman/location

A Laravel package that allows developers to retrieve a visitor's geographic location from their IP address using various online and local drivers. It supports multiple drivers including IpApi, IpData, IpInfo, MaxMind, and Cloudflare, with support for fallback drivers, custom driver implementation, and location mocking for testing via Location::fake().

Tokens
3.7K
Snippets
6
Records
31
Agent score
77%

What's inside stevebauman/location

  1. Set up MaxMind as a fallback driver

    master

    It is recommended to use MaxMind with a local .mmdb database as a fallback driver to handle rate limits from web services.

    1. Create a MaxMind account.
    2. Generate a license key in your profile.
    3. Add MAXMIND_LICENSE_KEY=your_key to your .env file.
    4. Configure the url in config/location.php (see Upgrading from v6).
    5. Run php artisan location:update to download the database to database/maxmind.
  2. Install the Location package

    master

    Install the package using Composer. After installation, publish the configuration file to create config/location.php.

    composer require stevebauman/location
    
    php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"
  3. Install and configure the Location package

    master

    The package integrates with Laravel via the LocationServiceProvider. To customize the package behavior, you can publish the configuration file to your application's config directory using the standard Laravel publishing command.

    After publishing, you can modify config/location.php to configure your preferred drivers and settings.

  4. Fake locations for testing

    master

    Use Location::fake() to mock location results during testing. You can provide an array mapping IP patterns to Position objects.

    Supported patterns:

    • Exact IP: '127.0.0.1'
    • Wildcard IP: '192.123.*.*'
    • Catch-all: '*'

    If no expectations are provided or no pattern matches, Location::get() returns false.

    use Stevebauman\Location\Position;
    use Stevebauman\Location\Facades\Location;
    
    // Mock specific IPs
    Location::fake([
        '127.0.0.1' => Position::make([
            'countryName' => 'United States',
            'countryCode' => 'US',
            // ...
        ]),
        '192.123.*.*' => Position::make([
            'countryName' => 'Canada',
            'countryCode' => 'CA',
            // ...
        ]),
    ]);
    
    // Mock all IPs
    Location::fake([
        '*' => Position::make([
            'countryName' => 'United States',
            'countryCode' => 'US',
            // ...
        ])
    ]);
    
    // No expectations (returns false)
    Location::fake();
  5. Retrieve a client's location

    master

    Use the Location::get() method without arguments to retrieve the location of the current visitor based on their IP address (via request()->ip()).

    Important: By default, testing.enabled is active in the configuration, which causes the returned IP to be in the USA. Disable this in config/location.php to retrieve the client's real IP address.

    use Stevebauman\Location\Facades\Location;
    
    if ($position = Location::get()) {
        // Successfully retrieved position.
        echo $position->countryName;
    } else {
        // Failed retrieving position.
    }
  6. Create a custom location driver

    master

    To implement a custom driver, extend the Stevebauman\Location\Drivers\Driver class and implement the process and hydrate methods.

    • process(Request $request): Should return a Illuminate\Support\Fluent object containing the raw data from your service.
    • hydrate(Position $position, Fluent $location): Should map the data from the Fluent object onto the Position object.
    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, register it in config/location.php:

    'driver' => App\\Location\\Drivers\\MyDriver::class,
  7. Create a custom HTTP driver

    master

    If your driver uses an HTTP service, extend Stevebauman\Location\Drivers\HttpDriver instead of the base Driver. This simplifies implementation by allowing you to only define the url and hydrate methods.

    namespace App\\Location\\Drivers;
    
    use Illuminate\Support\\Fluent;
    use Stevebauman\Location\Position;
    use Stevebauman\Location\Drivers\HttpDriver;
    
    class MyDriver extends HttpDriver
    {
        public function url(string $ip): string
        {
            return "http://driver-url.com?ip=$ip";
        }
    
        protected function hydrate(Position $position, Fluent $location): Position
        {
            $position->countryCode = $location->country_code;
            return $position;
        }
    }
  8. Configure the MaxMind driver

    master

    The MaxMind driver uses several configuration keys to manage both Web Service and Local database modes.

    Web Service Configuration

    Used when location.maxmind.web.enabled is set to true.

    • location.maxmind.web.user_id: The MaxMind user ID.
    • location.maxmind.license_key: The MaxMind license key (can also be provided via location.maxmind.license_key).
    • location.maxmind.web.options: An array of additional options for the MaxMind client.
    • location.maxmind.web.locales: An array of locales (defaults to ['en']).

    Local Database Configuration

    Used when the Web Service is disabled.

    • location.maxmind.local.path: The filesystem path to the .mmdb file (defaults to database_path('maxmind/GeoLite2-City.mmdb')).
    • location.maxmind.local.type: The level of detail to retrieve, either city or country (defaults to city).
    • location.maxmind.local.url: The URL used to download the database during an update (defaults to a MaxMind download URL using your license key).
  9. Configure the Ip2location.io driver

    master

    To use the Ip2locationio driver, you must provide an API token in your application's configuration. The driver retrieves this token from the location.ip2locationio.token configuration key.

    In your config/location.php file (or via your environment variables if mapped), ensure the following key is set:

    'ip2locationio' => [
        'token' => 'YOUR_IP2LOCATION_IO_TOKEN',
    ],
  10. Configure Cloudflare for location detection

    master

    To use the Cloudflare driver for location detection, you must ensure that Cloudflare is passing the required HTTP request headers to your application.

    Basic country detection is available via the cf-ipcountry header (available via the Cloudflare dashboard).

    For more granular data like city, longitude, latitude, and timezone, you must configure the relevant Managed Transforms in your Cloudflare dashboard. Without these transforms, the driver will only be able to resolve the countryCode and isoCode.