Install the Bundle
composer require cravler/maxmind-geoip-bundle:3.x-dev
config/bundles.php.Download MaxMind Databases
.mmdb files (e.g., GeoIP2-Country.mmdb) in resources/MaxMind/ (default path).Basic Usage Inject the service in a controller/service:
use Cravler\MaxMindGeoIpBundle\Service\GeoIpService;
public function __construct(private GeoIpService $geoIp) {}
public function getGeoData(Request $request) {
$ip = $request->getClientIp();
$country = $this->geoIp->getCountry($ip);
return $country->getCountry()->getIsoCode();
}
IP Lookup
GeoIpService for direct queries:
$country = $this->geoIp->getCountry($ip);
$city = $this->geoIp->getCity($ip);
$data = $this->geoIp->getCity($ip)->getLocation();
Request Integration
Request via an event subscriber:
// src/EventSubscriber/GeoIpSubscriber.php
public function onKernelRequest(GetResponseEvent $event) {
$request = $event->getRequest();
$request->attributes->set('geo', $this->geoIp->getAll($request->getClientIp()));
}
Caching
$cache = $this->cache->get($ip, function() use ($ip) {
return $this->geoIp->getCountry($ip);
});
Configuration Overrides
config/packages/cravler_max_mind_geo_ip.yaml:
cravler_max_mind_geo_ip:
path: '%kernel.project_dir%/var/geoip'
db:
country: 'custom-country.mmdb'
Dependency Injection
services:
App\Service\GeoIpDecorator:
decorates: cravler_max_mind_geo_ip.geo_ip
arguments: ['@cravler_max_mind_geo_ip.geo_ip.decorated']
Database Paths
.mmdb files in resources/MaxMind/ by default.path in config or ensure files are symlinked.Missing Databases
getCity() fails if GeoIP2-City.mmdb is missing.config/packages/ or use source to disable unused DBs.IPv6 Support
filter_var($ip, FILTER_VALIDATE_IP) before lookup.Performance
GeoIP2-City.mmdb) slow down first requests.License Key
license_key in config or use free GeoLite2 databases.config/packages/dev/cravler_max_mind_geo_ip.yaml:
client:
options:
verbose: true
mmdbdump tool to verify .mmdb files:
mmdbdump -i GeoIP2-Country.mmdb -b 1.1.1.1
Custom Data Mappers
Extend GeoIpService to add domain-specific logic:
class CustomGeoIpService extends GeoIpService {
public function getRiskScore($ip) {
$asn = $this->getAsn($ip);
// Custom risk logic...
}
}
Event Dispatching Trigger events on geo-data retrieval:
$this->eventDispatcher->dispatch(
new GeoIpEvent($ip, $data),
GeoIpEvents::ON_GEO_DATA_RETRIEVED
);
Cloud API Fallback Combine local DBs with MaxMind’s Cloud API:
public function getCountry($ip) {
try {
return parent::getCountry($ip);
} catch (Exception $e) {
return $this->cloudClient->lookup($ip);
}
}
Testing
Mock GeoIpService in tests:
$this->geoIp->method('getCountry')
->willReturn(new Country(['isoCode' => 'US']));
How can I help you explore Laravel packages today?