### CI/CD Integration Examples Source: https://github.com/stevebauman/location/blob/master/_autodocs/artisan-commands.md Examples for running the update command in GitHub Actions, Docker builds, and manual SSH deployments. ```yaml - name: Update Location Database run: php artisan location:update env: MAXMIND_LICENSE_KEY: ${{ secrets.MAXMIND_LICENSE_KEY }} ``` ```dockerfile # Update database during image build RUN php artisan location:update ``` ```bash # SSH into production server ssh user@production.com cd /var/www/app php artisan location:update ``` -------------------------------- ### Install Location Package Source: https://github.com/stevebauman/location/blob/master/_autodocs/quickstart.md Install the package via Composer and publish the configuration files. ```bash composer require stevebauman/location php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider" ``` -------------------------------- ### Usage Examples for isTesting Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Demonstrates configuration and usage of the testing mode check. ```php // In config/location.php 'testing' => [ 'enabled' => env('LOCATION_TESTING', true), ], // In code if ($request->isTesting()) { // Will use testing IP } ``` -------------------------------- ### Usage Examples for setIp Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Demonstrates setting, clearing, and chaining the setIp method. ```php $request->setIp('203.0.113.1'); // Now getIp() will return '203.0.113.1' // Clear manually set IP $request->setIp(null); // Now getIp() uses automatic detection // Fluent chaining $ip = $request->setIp('8.8.8.8')->getIp(); // "8.8.8.8" ``` -------------------------------- ### Example: Set IP Address Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Manually setting the IP address and using fluent chaining. ```php $request = LocationRequest::createFrom(request()); $request->setIp('8.8.8.8'); $ip = $request->getIp(); // "8.8.8.8" // Fluent chaining $request->setIp('203.0.113.1')->getIp(); // "203.0.113.1" ``` -------------------------------- ### Usage Examples for getTestingIp Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Demonstrates configuration and retrieval of the testing IP address. ```php // In config/location.php 'testing' => [ 'ip' => '66.102.0.0', 'enabled' => true, ], echo $request->getTestingIp(); // "66.102.0.0" ``` -------------------------------- ### Example: Get HTTP Headers Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Retrieving specific or all headers from the request. ```php $request = LocationRequest::createFrom(request()); // Get specific header $country = $request->getHeader('cf-ipcountry', 'US'); // "US" // Get all headers $all = $request->getHeader(); // array of headers ``` -------------------------------- ### IpInfo Request Example Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Example URL structures for IpInfo requests with and without tokens. ```php // Without token: http://ipinfo.io/8.8.8.8 // With token: http://ipinfo.io/8.8.8.8?token=TOKEN ``` -------------------------------- ### Fallback Chain Configuration Example Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Driver.md Demonstrates the order of execution when multiple drivers are configured for fallbacks. ```php // Configuration 'driver' => IpApi::class, 'fallbacks' => [IpInfo::class, MaxMind::class], // Result: If IpApi fails or returns empty: // 1. Try IpApi // 2. Try IpInfo // 3. Try MaxMind // 4. Return false ``` -------------------------------- ### Usage Examples for getIp Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Demonstrates retrieving IP addresses under normal, testing, and manual override conditions. ```php // Normal request $request = LocationRequest::createFrom($httpRequest); // IP = 203.0.113.1 $request->getIp(); // "203.0.113.1" // Testing mode enabled $request->getIp(); // "66.102.0.0" (testing IP) // Manually set IP $request->setIp('8.8.8.8'); $request->getIp(); // "8.8.8.8" ``` -------------------------------- ### IpApiPro Request Example Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Example of the request structure for the IpApiPro service. ```php // Calls: https://pro.ip-api.com/json/8.8.8.8?key=TOKEN&fields=... ``` -------------------------------- ### Example: Get IP Address Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Retrieving the IP address from a LocationRequest instance. ```php $request = LocationRequest::createFrom(request()); echo $request->getIp(); // "203.0.113.1" ``` -------------------------------- ### Usage Examples for getHeader Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Demonstrates retrieving specific headers or all headers with optional default values. ```php // Get single header $country = $request->getHeader('cf-ipcountry'); // Get with default $country = $request->getHeader('cf-ipcountry', 'US'); // Get all headers $all = $request->getHeader(); ``` -------------------------------- ### IpData Request Example Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Example URL structure for an IpData request. ```php // https://api.ipdata.co/8.8.8.8?api-key=TOKEN ``` -------------------------------- ### Update Progress Output Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-Special.md Example output displayed when running the update command. ```text Updating driver [Stevebauman\Location\Drivers\MaxMind]... Successfully updated driver [Stevebauman\Location\Drivers\MaxMind]. ``` -------------------------------- ### Use LocationRequest Source: https://github.com/stevebauman/location/blob/master/_autodocs/types.md Example of creating a LocationRequest from the current context and manually setting an IP. ```php $request = LocationRequest::createFrom(request()); $request->setIp('203.0.113.1'); $ip = $request->getIp(); // '203.0.113.1' ``` -------------------------------- ### Example Web Service Configuration Source: https://github.com/stevebauman/location/blob/master/_autodocs/configuration.md Configuration snippet enabling the MaxMind web service with custom locales. ```php 'maxmind' => [ 'license_key' => env('MAXMIND_LICENSE_KEY'), 'web' => [ 'enabled' => true, 'user_id' => env('MAXMIND_USER_ID'), 'license_key' => env('MAXMIND_LICENSE_KEY'), 'locales' => ['en', 'fr'], ], ], ``` -------------------------------- ### Retrieve location data with get() Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Driver.md Demonstrates the typical usage of the get() method, usually invoked by the LocationManager. ```php // Typically called by LocationManager, not directly $driver = app(IpApi::class); $request = LocationRequest::createFrom(request()); $position = $driver->get($request); ``` -------------------------------- ### Setup MaxMind Local Database Source: https://github.com/stevebauman/location/blob/master/_autodocs/configuration.md Steps to configure and download the local MaxMind database via environment variables and artisan commands. ```bash # 1. Create MaxMind account at https://www.maxmind.com # 2. Generate license key # 3. Set environment variable export MAXMIND_LICENSE_KEY=your_license_key # 4. Download database php artisan location:update # 5. Database stored at: database/maxmind/GeoLite2-City.mmdb ``` -------------------------------- ### Install Location Package Source: https://github.com/stevebauman/location/blob/master/_autodocs/README.md Use Composer to add the package to your Laravel project. ```bash composer require stevebauman/location ``` -------------------------------- ### Kloudend Request Example Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Demonstrates URL construction for Kloudend requests with and without an API token. ```php // Without token: https://ipapi.co/8.8.8.8/json // With token: https://ipapi.co/8.8.8.8/json?key=TOKEN ``` -------------------------------- ### Trigger DriverDoesNotExistException Source: https://github.com/stevebauman/location/blob/master/_autodocs/errors.md Example configuration causing the driver exception. ```php // config/location.php 'driver' => 'App\Location\Drivers\NonExistentDriver::class', // This throws DriverDoesNotExistException $manager = new LocationManager(); // Exception: The location driver [App\Location\Drivers\NonExistentDriver] // does not exist. Did you publish the configuration file? ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/stevebauman/location/blob/master/_autodocs/configuration.md Example of setting environment variables in a .env file for the Location package. ```bash APP_ENV=production LOCATION_TESTING=false # MaxMind MAXMIND_LICENSE_KEY=abc123xyz789 # API Tokens (optional) IPINFO_TOKEN=token123 IPDATA_TOKEN=token456 IP_API_TOKEN=token789 ``` -------------------------------- ### Driver Get Method Request Handling Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Demonstrates how the driver's get method receives the request object. ```php public function get(Request $request): Position|false { $data = $this->process($request); // Driver receives Request // ... } ``` -------------------------------- ### Ip2location.io Request Example Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Example URL structure for an Ip2location.io API request. ```php // https://api.ip2location.io/?key=TOKEN&ip=8.8.8.8 ``` -------------------------------- ### IpApi Request Example Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Retrieving location data using the IpApi driver via the Location facade. ```php use Stevebauman\Location\Facades\Location; $position = Location::get('8.8.8.8'); // Calls: http://ip-api.com/json/8.8.8.8?fields=status,message,country,... ``` -------------------------------- ### Configuring LocationFake Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationFake.md Examples of setting up fake location data using specific IPs, wildcards, or catch-all patterns. ```php use Stevebauman\Location\Position; use Stevebauman\Location\Facades\Location; Location::fake([ '127.0.0.1' => Position::make([ 'countryCode' => 'US', 'cityName' => 'New York', ]), ]); ``` ```php Location::fake([ '127.0.0.1' => Position::make([ 'countryCode' => 'US', 'cityName' => 'New York', ]), '192.168.1.1' => Position::make([ 'countryCode' => 'CA', 'cityName' => 'Toronto', ]), ]); ``` ```php Location::fake([ '192.168.*.*' => Position::make(['countryCode' => 'CA']), '10.0.*.*' => Position::make(['countryCode' => 'US']), '172.16.*.*' => Position::make(['countryCode' => 'GB']), ]); ``` ```php Location::fake([ '*' => Position::make(['countryCode' => 'US']), ]); // All IPs return the US position Location::get('any-ip'); ``` ```php Location::fake(); // All IPs return false Location::get('any-ip'); // false ``` -------------------------------- ### GeoPlugin Request Example Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Example URL structure for a GeoPlugin API request. ```php // http://www.geoplugin.net/json.gp?ip=8.8.8.8 ``` -------------------------------- ### Test DriverDoesNotExistException Source: https://github.com/stevebauman/location/blob/master/_autodocs/errors.md Example of asserting the exception in a test environment. ```php use Stevebauman\Location\Exceptions\DriverDoesNotExistException; public function test_throws_when_driver_not_found() { config()->set('location.driver', 'App\Drivers\InvalidDriver'); $this->expectException(DriverDoesNotExistException::class); $this->expectExceptionMessage('does not exist'); new LocationManager(); } ``` -------------------------------- ### Custom Driver Implementation Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Driver.md Example of extending HttpDriver to create a custom location provider. ```php 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\HttpDriver; class MyDriver extends HttpDriver { public function url(string $ip): string { return "https://api.example.com/geoip?ip=$ip"; } protected function hydrate(Position $position, Fluent $location): Position { $position->countryCode = $location->country_code; $position->countryName = $location->country_name; $position->cityName = $location->city; return $position; } } ``` -------------------------------- ### Implementing the Updatable Interface Source: https://github.com/stevebauman/location/blob/master/_autodocs/types.md Example implementation of the Updatable interface within a driver class. ```php class MaxMind extends Driver implements Updatable { public function update(Command $command): void { // Download latest MaxMind GeoLite2 database } } ``` -------------------------------- ### Kloudend Environment Variable Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Example of setting the Kloudend API token via environment variables. ```bash KLOUDEND_TOKEN=your_api_token ``` -------------------------------- ### IP Pattern Matching Examples Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationFake.md Demonstrates valid patterns for matching IP addresses using Laravel's Str::is() syntax. ```php // These patterns all match '192.168.1.50' '192.168.1.50' // Exact '192.168.1.*' // Single segment wildcard '192.168.*.*' // Multiple segment wildcard '192.*.*.*' // Even broader '*' // Catch-all ``` -------------------------------- ### Override Configuration Programmatically Source: https://github.com/stevebauman/location/blob/master/_autodocs/configuration.md Example of overriding the driver and reinitializing the Location service at runtime. ```php use Stevebauman\Location\Facades\Location; // Set driver at runtime config(['location.driver' => \Stevebauman\Location\Drivers\MaxMind::class]); // Reinitialize with new config Location::setDefaultDriver(); ``` -------------------------------- ### Catch LocationException Source: https://github.com/stevebauman/location/blob/master/_autodocs/errors.md Example of catching the base exception during location retrieval. ```php use Stevebauman\Location\Exceptions\LocationException; try { $position = Location::get(); } catch (LocationException $e) { log_error($e->getMessage()); } ``` -------------------------------- ### Retrieve Location via Cloudflare Headers Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-Special.md Example usage of the Location facade on a site proxied through Cloudflare. ```php // On a Cloudflare-proxied site $position = Location::get(); // Reads headers: // CF-IPCountry: US // CF-IPCity: San Francisco // CF-IPLatitude: 37.7749 // CF-IPLongitude: -122.4194 echo $position->countryCode; // "US" echo $position->cityName; // "San Francisco" ``` -------------------------------- ### Local Database Lookup Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-Special.md Example of performing a location lookup using the local database mode. ```php $position = Location::get('8.8.8.8'); // Reads from: database/maxmind/GeoLite2-City.mmdb ``` -------------------------------- ### Resolve HTTP Requests Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/HttpDriver.md Method signature for setting a custom HTTP resolver and examples for mocking or adding headers. ```php public static function resolveHttpBy(Closure $callback): void ``` ```php use Illuminate\ Support\\Facades\\Http; // In tests: mock HTTP responses HttpDriver::resolveHttpBy(function ($http) { return $http->fake([ 'https://api.example.com/*' => Http::response(['country' => 'US']) ]); }); // Add custom header HttpDriver::resolveHttpBy(function ($http) { return $http->withHeader('X-Custom', 'value'); }); ``` -------------------------------- ### Testing with LocationFake Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationFake.md Practical examples of using LocationFake within Laravel test cases to simulate location-based logic. ```php use Stevebauman\Location\Position; use Stevebauman\Location\Facades\Location; use Tests\TestCase; class CountryBlockingTest extends TestCase { public function test_blocks_users_from_restricted_countries() { Location::fake([ '203.0.113.1' => Position::make(['countryCode' => 'CN']), '198.51.100.1' => Position::make(['countryCode' => 'US']), ]); $response = $this->get('/api/data', ['X-Forwarded-For' => '203.0.113.1']); $this->assertEquals(403, $response->status()); $response = $this->get('/api/data', ['X-Forwarded-For' => '198.51.100.1']); $this->assertEquals(200, $response->status()); } } ``` ```php public function test_sets_locale_from_location() { Location::fake([ '203.0.113.1' => Position::make(['countryCode' => 'FR']), ]); $response = $this->get('/api/content'); $this->assertEquals('fr', app()->getLocale()); } ``` ```php public function test_uses_default_locale_when_location_unknown() { Location::fake(); // Empty fake $response = $this->get('/api/content'); $this->assertEquals('en', app()->getLocale()); } ``` -------------------------------- ### Extending Location with Macros Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Location-Facade.md Use the macro method to add custom functionality to the Location facade. This example defines a getCountry helper that retrieves the country code from an IP address. ```php Location::macro('getCountry', function(string $ip = null) { return $this->get($ip)?->countryCode; }); $country = Location::getCountry('8.8.8.8'); ``` -------------------------------- ### Enable Production Mode Source: https://github.com/stevebauman/location/blob/master/_autodocs/quickstart.md Configure testing mode via environment variables and the configuration file. ```bash # .env LOCATION_TESTING=false ``` ```php // config/location.php 'testing' => [ 'enabled' => env('LOCATION_TESTING', false), ], ``` -------------------------------- ### Retrieve Specific IP Location Source: https://github.com/stevebauman/location/blob/master/readme.md Get location data for a specific IP address by passing it as an argument to the get method. ```php $position = Location::get('192.168.1.1'); ``` -------------------------------- ### Get HTTP Header Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Signature for the getHeader method. ```php public function getHeader(?string $key = null, string|array|null $default = null): string|array|null ``` -------------------------------- ### Configure Drivers for Development Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-Special.md Sets IpApi as the primary driver for speed and cost-efficiency, with a local MaxMind database as a backup. ```php 'driver' => IpApi::class, // Fast, free 'fallbacks' => [ MaxMind::class, // Local database backup ], ``` -------------------------------- ### Configure driver fallback chain with fallback() Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Driver.md Shows how to link multiple drivers together to create a sequential fallback chain. ```php $primary = app(IpApi::class); $fallback1 = app(IpInfo::class); $fallback2 = app(MaxMind::class); $primary->fallback($fallback1); $fallback1->fallback($fallback2); // Now: IpApi -> IpInfo -> MaxMind ``` -------------------------------- ### Prepare database directory Source: https://github.com/stevebauman/location/blob/master/_autodocs/artisan-commands.md Ensure the database directory is writable and the maxmind subdirectory exists. ```bash chmod 755 database/ mkdir -p database/maxmind chmod 755 database/maxmind ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/stevebauman/location/blob/master/_autodocs/README.md Set the testing mode and MaxMind license key in your .env file. ```bash # .env LOCATION_TESTING=false MAXMIND_LICENSE_KEY=your_license_key ``` -------------------------------- ### Publish Configuration File Source: https://github.com/stevebauman/location/blob/master/_autodocs/errors.md Run this artisan command to generate the missing configuration file if config('location') returns null. ```bash php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider" ``` -------------------------------- ### Configure Fallback Chain for Production Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-Special.md Defines a driver sequence using MaxMind as the primary source with Cloudflare and IpApi as fallbacks. ```php 'driver' => MaxMind::class, 'fallbacks' => [ Cloudflare::class, IpApi::class, ], ``` -------------------------------- ### Implement Request in Driver Process Method Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Shows the abstract process method signature and a sample implementation that retrieves the IP address from the request. ```php abstract protected function process(Request $request): Fluent|false; // Implementation protected function process(Request $request): Fluent|false { $ip = $request->getIp(); // Use IP to fetch geolocation data } ``` -------------------------------- ### Iterate Over Available Drivers Source: https://github.com/stevebauman/location/blob/master/_autodocs/quickstart.md Access and inspect all configured location drivers. ```php foreach (Location::drivers() as $driver) { echo get_class($driver); } ``` -------------------------------- ### Configure MaxMind License Source: https://github.com/stevebauman/location/blob/master/_autodocs/quickstart.md Set the license key and update the database via artisan command. ```bash # .env MAXMIND_LICENSE_KEY=your_license_key # Download database php artisan location:update ``` -------------------------------- ### Configure Driver Class Reference Source: https://github.com/stevebauman/location/blob/master/_autodocs/errors.md Ensure the driver configuration uses the full class reference with ::class to avoid DriverDoesNotExistException. ```php // config/location.php 'driver' => Stevebauman\Location\Drivers\IpApi::class, // Correct: full class reference // NOT: 'driver' => 'Stevebauman\Location\Drivers\IpApi', // String without ::class ``` -------------------------------- ### Iterate over drivers with Location::drivers() Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Location-Facade.md Retrieves all initialized drivers for introspection or bulk operations. ```php foreach (Location::drivers() as $driver) { if ($driver instanceof \Stevebauman\Location\Drivers\Updatable) { $driver->update($command); } } ``` -------------------------------- ### GET https://api.ip2location.io/ Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Retrieves geolocation data from the Ip2location.io service for a given IP address. ```APIDOC ## GET https://api.ip2location.io/ ### Description Retrieves geolocation data from the Ip2location.io service for a given IP address. Requires an API token for authentication. ### Method GET ### Endpoint https://api.ip2location.io/ ### Query Parameters - **key** (string) - Required - Your API token. - **ip** (string) - Required - The IP address to look up. ### Request Example https://api.ip2location.io/?key=TOKEN&ip=8.8.8.8 ### Response - **country_name** (string) - Country name - **country_code** (string) - Country code - **region_name** (string) - Region name - **region_code** (string) - Region code - **city_name** (string) - City name - **zip_code** (string) - ZIP code - **latitude** (float) - Latitude - **longitude** (float) - Longitude - **timezone** (string) - Timezone - **currency** (object) - Contains currency code - **geotargeting** (object) - Contains metro code - **area_code** (string) - Area code ``` -------------------------------- ### Environment Variable Reference Source: https://github.com/stevebauman/location/blob/master/_autodocs/README.md List of all supported environment variables for testing, MaxMind, and various API providers. ```bash # Testing LOCATION_TESTING=false # MaxMind MAXMIND_LICENSE_KEY=key MAXMIND_USER_ID=user_id # API Tokens IP_API_TOKEN=token IPINFO_TOKEN=token IPDATA_TOKEN=token IP2LOCATIONIO_TOKEN=token KLOUDEND_TOKEN=token ``` -------------------------------- ### GET http://www.geoplugin.net/json.gp Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Retrieves geolocation data from the GeoPlugin service for a given IP address. ```APIDOC ## GET http://www.geoplugin.net/json.gp ### Description Retrieves geolocation data from the GeoPlugin service for a given IP address. ### Method GET ### Endpoint http://www.geoplugin.net/json.gp ### Query Parameters - **ip** (string) - Required - The IP address to look up. ### Request Example http://www.geoplugin.net/json.gp?ip=8.8.8.8 ### Response - **geoplugin_countryCode** (string) - Country code - **geoplugin_countryName** (string) - Country name - **geoplugin_regionCode** (string) - Region code - **geoplugin_regionName** (string) - Region name - **geoplugin_city** (string) - City name - **geoplugin_latitude** (string) - Latitude - **geoplugin_longitude** (string) - Longitude - **geoplugin_areaCode** (string) - Area code - **geoplugin_timezone** (string) - Timezone ``` -------------------------------- ### Location::drivers() Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Location-Facade.md Returns all initialized drivers, including primary and fallback drivers. ```APIDOC ## Location::drivers() ### Description Returns all loaded drivers (primary and fallbacks). Useful for introspection or bulk operations. ### Return Type - **Driver[]** - All initialized drivers. ``` -------------------------------- ### Implement isTesting Logic Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md The internal implementation for checking the testing configuration. ```php protected function isTesting(): bool { return config('location.testing.enabled', true); } ``` -------------------------------- ### Configure MaxMind license key Source: https://github.com/stevebauman/location/blob/master/_autodocs/artisan-commands.md Set the required environment variable for MaxMind database downloads. ```bash # .env MAXMIND_LICENSE_KEY=your_license_key_here ``` -------------------------------- ### GET http://ipinfo.io/{ip} Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Retrieves location data for a given IP address using the ipinfo.io service. ```APIDOC ## GET http://ipinfo.io/{ip} ### Description Retrieves location data for a specific IP address from the ipinfo.io service. ### Method GET ### Endpoint http://ipinfo.io/{ip} ### Parameters #### Path Parameters - **ip** (string) - Required - The IP address to look up. #### Query Parameters - **token** (string) - Optional - API token for authentication. ### Request Example http://ipinfo.io/8.8.8.8?token=TOKEN ### Response #### Success Response (200) - **Country** (string) - Code - **Region** (string) - Name - **City** (string) - Name - **Postal code** (string) - Postal code - **Timezone** (string) - Timezone - **loc** (string) - Combined latitude and longitude (lat,lon) ``` -------------------------------- ### GET https://api.ipdata.co/{ip} Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Retrieves location data for a given IP address using the ipdata.co service. ```APIDOC ## GET https://api.ipdata.co/{ip} ### Description Retrieves location data for a specific IP address from the ipdata.co service. ### Method GET ### Endpoint https://api.ipdata.co/{ip} ### Parameters #### Path Parameters - **ip** (string) - Required - The IP address to look up. #### Query Parameters - **api-key** (string) - Optional - API token for authentication. ### Request Example https://api.ipdata.co/8.8.8.8?api-key=TOKEN ### Response #### Success Response (200) - **Country** (string) - Name and code - **Region** (string) - Name and code - **City** (string) - Name - **Postal code** (string) - Postal code - **Latitude/Longitude** (float) - Coordinates - **Timezone** (object) - Timezone details - **Currency** (object) - Currency details ``` -------------------------------- ### IpApi Configuration Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Setting the default driver to IpApi in the configuration file. ```php 'driver' => \Stevebauman\Location\Drivers\IpApi::class, ``` -------------------------------- ### get(?string $ip) Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationFake.md Retrieves the faked Position object for a given IP address based on configured patterns. ```APIDOC ## get(?string $ip) ### Description Returns the faked Position for the given IP address. Matches the IP against patterns in the configured requests, supporting wildcards. If no pattern matches, returns false. ### Method public function get(?string $ip = null): Position|false ### Parameters - **ip** (string|null) - Optional - IP address to look up (defaults to '127.0.0.1') ### Returns - **Position|false** - The matching Position instance or false if no pattern matches. ``` -------------------------------- ### Implement Custom Driver with Exception Handling Source: https://github.com/stevebauman/location/blob/master/_autodocs/errors.md Use the rescue helper within the process method to catch exceptions and return false, enabling seamless driver fallback. ```php namespace App\Location\Drivers; use Stevebauman\Location\Drivers\HttpDriver; class CustomDriver extends HttpDriver { public function url(string $ip): string { return "https://api.example.com/locate/$ip"; } protected function process(Request $request): Fluent|false { // HttpDriver::process() automatically catches exceptions // and returns false, allowing fallback return rescue(function () use ($request) { $response = $this->http()->get($this->url($request->getIp())); throw_if($response->failed()); return new Fluent($response->json()); }, false, false); } } ``` -------------------------------- ### GET https://pro.ip-api.com/json/{ip} Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Retrieves geolocation information for a given IP address using the authenticated pro.ip-api.com service. ```APIDOC ## GET https://pro.ip-api.com/json/{ip} ### Description Retrieves geolocation data for the specified IP address using the Pro service, which requires an API token. ### Method GET ### Endpoint https://pro.ip-api.com/json/{ip} ### Parameters #### Path Parameters - **ip** (string) - Required - The IP address to look up. #### Query Parameters - **key** (string) - Required - The API token for authentication. ``` -------------------------------- ### Configure HTTP Client Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/HttpDriver.md Method signature for the internal HTTP client and the default configuration structure. ```php protected function http(): PendingRequest ``` ```php 'http' => [ 'timeout' => 3, 'connect_timeout' => 3, ], ``` -------------------------------- ### IpApiPro Configuration Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Configuring the IpApiPro driver with an API token. ```php 'driver' => \Stevebauman\Location\Drivers\IpApiPro::class, 'ip_api' => [ 'token' => env('IP_API_TOKEN'), ], ``` -------------------------------- ### GET http://ip-api.com/json/{ip} Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Retrieves geolocation information for a given IP address using the free ip-api.com service. ```APIDOC ## GET http://ip-api.com/json/{ip} ### Description Retrieves geolocation data for the specified IP address. This is the default driver for the package. ### Method GET ### Endpoint http://ip-api.com/json/{ip} ### Parameters #### Path Parameters - **ip** (string) - Required - The IP address to look up. ### Response #### Success Response (200) - **Country** (string) - Country name and code - **Region** (string) - Region/state name and code - **City** (string) - City name - **Zip** (string) - ZIP code - **Lat/Lon** (float) - Latitude and longitude - **Timezone** (string) - Timezone information - **Currency** (string) - Currency code - **ISP** (string) - ISP/organization information ``` -------------------------------- ### GET https://ipapi.co/{ip}/json Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Retrieves detailed location data for a given IP address using the Kloudend service. ```APIDOC ## GET https://ipapi.co/{ip}/json ### Description Retrieves comprehensive location information including city, region, coordinates, and timezone for a given IP address. ### Method GET ### Endpoint https://ipapi.co/{ip}/json ### Parameters #### Path Parameters - **ip** (string) - Required - The IP address to look up. #### Query Parameters - **key** (string) - Optional - API token for authentication. ### Request Example https://ipapi.co/8.8.8.8/json?key=TOKEN ### Response #### Success Response (200) - **Country name and code** (string) - Country details. - **Region code and name** (string) - Region details. - **City name** (string) - City name. - **Postal code** (string) - Postal code. - **Latitude and longitude** (float) - Geographic coordinates. - **Timezone** (string) - Timezone identifier. - **Currency code** (string) - Currency code. ``` -------------------------------- ### Configure and Retrieve Faked Locations Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationFake.md Demonstrates setting up multiple IP patterns and retrieving the corresponding faked position data. ```php Location::fake([ '127.0.0.1' => Position::make(['countryCode' => 'US']), '192.168.*.*' => Position::make(['countryCode' => 'CA']), '*' => Position::make(['countryCode' => 'GB']), ]); Location::get('127.0.0.1'); // Returns US position Location::get('192.168.1.50'); // Returns CA position Location::get('10.0.0.1'); // Returns GB position (catch-all) Location::get('203.0.113.1'); // Returns false (no match before catch-all) ``` -------------------------------- ### Accessing Fluent Data Source: https://github.com/stevebauman/location/blob/master/_autodocs/types.md Demonstrates initializing a Fluent object and accessing its data via property and array syntax. ```php use Illuminate\Support\Fluent; $data = new Fluent([ 'country' => 'United States', 'city' => 'New York', ]); echo $data->country; // "United States" echo $data['city']; // "New York" ``` -------------------------------- ### setDriver(Driver $driver): static Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationManager.md Sets the active driver for location lookups, making it the primary driver for subsequent get() calls. ```APIDOC ## setDriver(Driver $driver) ### Description Sets the active driver for location lookups. The provided driver becomes the primary driver used for all subsequent get() calls. ### Parameters - **$driver** (Driver) - Required - The driver instance to activate. ### Response - **Return Type** (static) - Returns the instance for method chaining. ``` -------------------------------- ### Handle Configuration Exceptions Source: https://github.com/stevebauman/location/blob/master/_autodocs/README.md Catch DriverDoesNotExistException when initializing the LocationManager with an invalid driver. ```php try { new LocationManager(); // May throw DriverDoesNotExistException } catch (DriverDoesNotExistException $e) { // Invalid driver in configuration } ``` -------------------------------- ### Retrieve Client Location Source: https://github.com/stevebauman/location/blob/master/readme.md Get the current visitor's location using the Location facade. Note that testing mode is enabled by default. ```php use Stevebauman\Location\Facades\Location; if ($position = Location::get()) { // Successfully retrieved position. echo $position->countryName; } else { // Failed retrieving position. } ``` -------------------------------- ### Configure HTTP Client Options Source: https://github.com/stevebauman/location/blob/master/_autodocs/configuration.md Sets connection and request timeouts for HTTP driver requests. ```php 'http' => [ 'timeout' => 3, 'connect_timeout' => 3, ], ``` ```php 'http' => [ 'timeout' => 10, 'connect_timeout' => 5, ], ``` -------------------------------- ### get(Request $request) Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Driver.md Retrieves location data based on the provided request. This method orchestrates the retrieval, validation, and hydration of a Position object. ```APIDOC ## get(Request $request) ### Description Main entry point for location retrieval. Orchestrates the retrieval workflow: calls process() to fetch data, validates it, calls hydrate() to populate the Position object, and returns it. If the data is empty or invalid, falls back to the next driver in the chain. ### Parameters - **$request** (Request) - Required - Request object containing IP address and headers ### Return Type Position|false ``` -------------------------------- ### GET https://api.ipinfo.io/lite/{ip} Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Retrieves minimal location data (country code and name) for a given IP address using the IpInfoLite service. ```APIDOC ## GET https://api.ipinfo.io/lite/{ip} ### Description Retrieves minimal location data for a given IP address. This endpoint is optimized for high-volume requests. ### Method GET ### Endpoint https://api.ipinfo.io/lite/{ip} ### Parameters #### Path Parameters - **ip** (string) - Required - The IP address to look up. ### Response #### Success Response (200) - **Country code** (string) - The ISO country code. - **Country name** (string) - The full name of the country. ``` -------------------------------- ### Define configuration types Source: https://github.com/stevebauman/location/blob/master/_autodocs/types.md Structure of the location.php configuration file defining drivers, fallbacks, and service-specific settings. ```php 'driver' => string // Class name of primary driver 'fallbacks' => array // Array of driver class names 'position' => string // Position class name (default: Position::class) 'http' => [ 'timeout' => int, 'connect_timeout' => int, ] 'testing' => [ 'enabled' => bool, 'ip' => string, // Default: '66.102.0.0' ] 'maxmind' => [ 'license_key' => string|null, 'web' => [ 'enabled' => bool, 'user_id' => string|int|null, 'license_key' => string|null, 'locales' => array, 'options' => array, ], 'local' => [ 'type' => 'city'|'country', 'path' => string, 'url' => string, ], ] 'ip_api' => ['token' => string|null] 'ipinfo' => ['token' => string|null] 'ipdata' => ['token' => string|null] 'ip2locationio' => ['token' => string|null] 'kloudend' => ['token' => string|null] ``` -------------------------------- ### Package File Structure Source: https://github.com/stevebauman/location/blob/master/_autodocs/README.md Overview of the source directory organization for the location package. ```text src/ ├── LocationManager.php # Core orchestrator ├── LocationRequest.php # Request implementation ├── LocationFake.php # Test double ├── Position.php # Location data container ├── Request.php # Request interface ├── Facades/ │ └── Location.php # Static facade ├── Drivers/ │ ├── Driver.php # Abstract base │ ├── HttpDriver.php # HTTP base │ ├── IpApi.php # HTTP drivers (8 total) │ ├── MaxMind.php # Database driver │ └── Cloudflare.php # Header driver ├── Exceptions/ │ ├── LocationException.php │ └── DriverDoesNotExistException.php └── Commands/ └── Update.php # Database update command ``` -------------------------------- ### get(?string $ip = null): Position|false Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationManager.md Retrieves geographic location data for the specified IP address. If no IP is provided, it attempts to determine the location from the current HTTP request. ```APIDOC ## get(?string $ip = null) ### Description Retrieves geographic location data for the specified IP address. If no IP is provided, attempts to determine location from the current HTTP request. Returns the populated Position object on success or false if all drivers fail to return location data. ### Parameters - **$ip** (string|null) - Optional - IP address to lookup. If null, uses the current request IP address. ### Response - **Return Type** (Position|false) - The location data or false on failure. ``` -------------------------------- ### Configure API Tokens Source: https://github.com/stevebauman/location/blob/master/_autodocs/quickstart.md Set required API tokens for various location services in the environment file. ```bash # .env IPINFO_TOKEN=your_token IPDATA_TOKEN=your_token IP_API_TOKEN=your_token ``` -------------------------------- ### Testing with Facade Swapping Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Location-Facade.md Use the fake method to mock location responses during unit testing. ```php use Stevebauman\Location\Facades\Location; public function test_location_detection() { Location::fake([ '203.0.113.1' => Position::make([ 'countryCode' => 'US', 'cityName' => 'San Francisco', ]), ]); $position = Location::get('203.0.113.1'); $this->assertEquals('US', $position->countryCode); $this->assertEquals('San Francisco', $position->cityName); } ``` -------------------------------- ### drivers(): Driver[] Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationManager.md Returns all loaded driver instances, including the primary driver and all fallback drivers in the chain. ```APIDOC ## drivers() ### Description Returns all loaded driver instances, including the primary driver and all fallback drivers in the chain. ### Response - **Return Type** (Driver[]) - Array of all initialized driver instances. ``` -------------------------------- ### Registering the Location Facade Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Location-Facade.md Add the alias to the aliases array in config/app.php if not using automatic discovery. ```php 'aliases' => [ 'Location' => Stevebauman\Location\Facades\Location, ], ``` -------------------------------- ### Test multiple IP addresses Source: https://github.com/stevebauman/location/blob/master/_autodocs/quickstart.md Demonstrates mocking multiple distinct IP addresses to ensure they return their respective configured locations. ```php public function test_different_ips_return_different_locations() { Location::fake([ '8.8.8.8' => Position::make(['countryCode' => 'US']), '1.1.1.1' => Position::make(['countryCode' => 'AU']), ]); $us = Location::get('8.8.8.8'); $au = Location::get('1.1.1.1'); $this->assertEquals('US', $us->countryCode); $this->assertEquals('AU', $au->countryCode); } ``` -------------------------------- ### Implement getTestingIp Logic Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md The internal implementation for retrieving the testing IP from configuration. ```php protected function getTestingIp(): string { return config('location.testing.ip', '66.102.0.0'); } ``` -------------------------------- ### IpApiPro Environment Variable Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Setting the API token in the environment file. ```bash IP_API_TOKEN=your_pro_api_token ``` -------------------------------- ### Integrating with Dependency Injection Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Location-Facade.md The facade and the LocationManager class can be used interchangeably within controllers. ```php use Stevebauman\Location\LocationManager; class UserController { public function __construct(LocationManager $location) {} public function store() { // Both are equivalent $position1 = Location::get(); $position2 = $this->location->get(); } } ``` -------------------------------- ### View class hierarchy Source: https://github.com/stevebauman/location/blob/master/_autodocs/types.md Visual representation of the package's class and interface inheritance structure. ```text Exception └── LocationException └── DriverDoesNotExistException Driver (abstract) ├── HttpDriver (abstract) │ ├── IpApi │ ├── IpApiPro │ ├── IpData │ ├── IpInfo │ ├── IpInfoLite │ ├── Kloudend │ ├── GeoPlugin │ └── Ip2locationio └── Cloudflare └── MaxMind (also implements Updatable) Illuminate\Http\Request └── LocationRequest (implements Request) Arrayable └── Position Facade └── Location (proxies to LocationManager) LocationManager └── LocationFake Interfaces: ├── Request ├── Updatable └── Arrayable (from Illuminate) ``` -------------------------------- ### Create Position Instance with make() Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Position.md Creates a new Position instance using an array of attributes. Keys are automatically converted from snake_case to camelCase. ```php $position = Position::make([ 'countryName' => 'United States', 'countryCode' => 'US', 'cityName' => 'New York', 'latitude' => '40.7128', 'longitude' => '-74.0060', 'timezone' => 'America/New_York', ]); // From snake_case array keys: $position = Position::make([ 'country_name' => 'Canada', 'country_code' => 'CA', 'city_name' => 'Toronto', ]); ``` -------------------------------- ### Instantiate LocationManager Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationManager.md Manual instantiation of the manager, typically handled by the service provider. ```php // Typically instantiated and bound by the service provider $manager = new LocationManager(); ``` -------------------------------- ### Instantiate LocationFake Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationFake.md Creates a new instance of the fake location manager with a map of IP patterns to Position objects. ```php $fake = new LocationFake($manager, [ '127.0.0.1' => Position::make(['countryCode' => 'US']), ]); ``` -------------------------------- ### Access Initialized Drivers Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/LocationManager.md Retrieve all loaded driver instances for introspection or maintenance. ```php $allDrivers = Location::drivers(); foreach ($allDrivers as $driver) { if ($driver instanceof \Stevebauman\Location\Drivers\Updatable) { $driver->update($command); } } ``` -------------------------------- ### Handle Driver Fallback Success Source: https://github.com/stevebauman/location/blob/master/_autodocs/errors.md Demonstrates that the system automatically attempts the next driver in the chain if the primary driver fails. ```php // If primary driver times out or errors, // the next driver in the chain is attempted $position = Location::get(); if ($position) { // Successfully retrieved from a fallback driver } ``` -------------------------------- ### Configure Environment-Specific Drivers Source: https://github.com/stevebauman/location/blob/master/_autodocs/configuration.md Set the driver and HTTP timeout settings based on the application environment. ```php // config/location.php return [ 'driver' => env('APP_ENV') === 'production' ? Stevebauman\Location\Drivers\MaxMind::class : Stevebauman\Location\Drivers\IpApi::class, 'testing' => [ 'enabled' => env('LOCATION_TESTING', env('APP_ENV') !== 'production'), ], 'http' => [ 'timeout' => env('LOCATION_TIMEOUT', 3), 'connect_timeout' => env('LOCATION_CONNECT_TIMEOUT', 3), ], ]; ``` -------------------------------- ### Implement process method in custom driver Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Driver.md Subclasses must implement this method to fetch raw location data from their backend service. It should return a Fluent object or false on failure. ```php protected function process(Request $request): Fluent|false { return rescue(function () use ($request) { $response = Http::get("https://api.example.com/location", [ 'ip' => $request->getIp() ]); return new Fluent($response->json()); }, false, false); } ``` -------------------------------- ### Implement getHeader Logic Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md The internal implementation for retrieving headers via the parent class. ```php public function getHeader(?string $key = null, string|array|null $default = null): string|array|null { return parent::header($key, $default); } ``` -------------------------------- ### Web Service Mode Configuration Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-Special.md Configuration snippet to enable the MaxMind web service mode. ```php 'maxmind' => [ 'web' => [ 'enabled' => true, 'user_id' => env('MAXMIND_USER_ID'), 'license_key' => env('MAXMIND_LICENSE_KEY'), ], ], ``` -------------------------------- ### Troubleshoot Location Failures Source: https://github.com/stevebauman/location/blob/master/_autodocs/quickstart.md Verify testing mode configuration and catch driver exceptions to diagnose why location lookups might return false. ```php // Check testing mode config('location.testing.enabled'); // Should be false in production // Check driver availability try { $drivers = Location::drivers(); } catch (Exception $e) { echo "Driver error: " . $e->getMessage(); } ``` -------------------------------- ### Configure Default Driver Source: https://github.com/stevebauman/location/blob/master/_autodocs/quickstart.md Set the primary driver for location resolution in the configuration file. ```php // config/location.php use Stevebauman\Location\Drivers\MaxMind; return [ 'driver' => MaxMind::class, ]; ``` -------------------------------- ### Create LocationRequest manually for testing Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Request.md Instantiate a LocationRequest from an existing request and manually set the IP address for testing purposes. ```php $request = LocationRequest::createFrom(request()); $request->setIp('8.8.8.8'); $driver = app(IpApi::class); $position = $driver->get($request); ``` -------------------------------- ### IpInfo Configuration Source: https://github.com/stevebauman/location/blob/master/_autodocs/api-reference/Drivers-HTTP.md Configuration structure for the IpInfo service. ```php 'ipinfo' => [ 'token' => env('IPINFO_TOKEN'), ], ```