stevebauman/location
repository·master·Indexed 23 days ago
https://github.com/stevebauman/locationA 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().
What's inside stevebauman/location
- You can specify multiple fallback drivers in your configuration. If the primary driver fails (e.g., due to a 400/500 error from an API), the package will automatically attempt to use the next driver in the list.
Set up MaxMind as a fallback driver
masterIt is recommended to use MaxMind with a local
.mmdbdatabase as a fallback driver to handle rate limits from web services.- Create a MaxMind account.
- Generate a license key in your profile.
- Add
MAXMIND_LICENSE_KEY=your_keyto your.envfile. - Configure the
urlinconfig/location.php(see Upgrading from v6). - Run
php artisan location:updateto download the database todatabase/maxmind.
Install the Location package
masterInstall 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"Install and configure the Location package
masterThe package integrates with Laravel via the
LocationServiceProvider. To customize the package behavior, you can publish the configuration file to your application'sconfigdirectory using the standard Laravel publishing command.After publishing, you can modify
config/location.phpto configure your preferred drivers and settings.Fake locations for testing
masterUse
Location::fake()to mock location results during testing. You can provide an array mapping IP patterns toPositionobjects.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()returnsfalse.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();- Exact IP:
Retrieve a client's location
masterUse the
Location::get()method without arguments to retrieve the location of the current visitor based on their IP address (viarequest()->ip()).Important: By default,
testing.enabledis active in the configuration, which causes the returned IP to be in the USA. Disable this inconfig/location.phpto 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. }Create a custom location driver
masterTo implement a custom driver, extend the
Stevebauman\Location\Drivers\Driverclass and implement theprocessandhydratemethods.process(Request $request): Should return aIlluminate\Support\Fluentobject containing the raw data from your service.hydrate(Position $position, Fluent $location): Should map the data from theFluentobject onto thePositionobject.
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,Create a custom HTTP driver
masterIf your driver uses an HTTP service, extend
Stevebauman\Location\Drivers\HttpDriverinstead of the baseDriver. This simplifies implementation by allowing you to only define theurlandhydratemethods.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; } }Retrieve the location of a specific IP address
masterPass a specific IP address string to the
Location::get()method to retrieve its location data.$position = Location::get('192.168.1.1');Configure the MaxMind driver
masterThe MaxMind driver uses several configuration keys to manage both Web Service and Local database modes.
Web Service Configuration
Used when
location.maxmind.web.enabledis set totrue.location.maxmind.web.user_id: The MaxMind user ID.location.maxmind.license_key: The MaxMind license key (can also be provided vialocation.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.mmdbfile (defaults todatabase_path('maxmind/GeoLite2-City.mmdb')).location.maxmind.local.type: The level of detail to retrieve, eithercityorcountry(defaults tocity).location.maxmind.local.url: The URL used to download the database during an update (defaults to a MaxMind download URL using your license key).
Configure the Ip2location.io driver
masterTo use the
Ip2locationiodriver, you must provide an API token in your application's configuration. The driver retrieves this token from thelocation.ip2locationio.tokenconfiguration key.In your
config/location.phpfile (or via your environment variables if mapped), ensure the following key is set:'ip2locationio' => [ 'token' => 'YOUR_IP2LOCATION_IO_TOKEN', ],Configure Cloudflare for location detection
masterTo 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-ipcountryheader (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
countryCodeandisoCode.