Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Maxmind Binary Provider Laravel Package

geocoder-php/maxmind-binary-provider

MaxMind Binary provider for the PHP Geocoder library. Lookup geolocation data from local MaxMind GeoIP2/GeoLite2 binary databases without external API calls. Useful for fast, offline IP-to-location resolution in PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require geocoder-php/maxmind-binary-provider
    

    Ensure geocoder-php/geocoder is also installed (required dependency).

  2. Basic Setup

    • Download a MaxMind GeoLite2 or GeoIP2 database (e.g., GeoLite2-City.mmdb).
    • Place the .mmdb file in a secure, accessible directory (e.g., storage/maxmind/).
  3. First Query

    use GeoCoder\Geocoder;
    use GeoCoder\Provider\MaxMind\BinaryProvider;
    
    $geocoder = new Geocoder();
    $geocoder->addProvider(BinaryProvider::fromPath('/path/to/GeoLite2-City.mmdb'));
    
    $result = $geocoder->geocode('192.0.2.1'); // IP address
    // or
    $result = $geocoder->reverse('192.0.2.1'); // Reverse geocoding (if supported)
    
  4. Key Files to Reference


Implementation Patterns

Common Workflows

  1. IP Geocoding

    $geocoder->geocode('8.8.8.8')->get();
    // Returns collection of locations (e.g., city, country, coordinates).
    
  2. Reverse Geocoding (Limited)

    • MaxMind binary providers primarily support forward geocoding (IP → location).
    • For reverse (coordinates → location), use a different provider (e.g., GoogleMapsProvider).
  3. Caching Responses

    $geocoder->addProvider(
        BinaryProvider::fromPath('/path/to/db.mmdb')
            ->withCache(new \GeoCoder\Cache\ArrayCache())
    );
    
  4. Environment-Specific Config

    // config/geocoder.php
    'providers' => [
        'maxmind' => [
            'path' => env('MAXMIND_DB_PATH', storage_path('maxmind/GeoLite2-City.mmdb')),
            'cache' => env('GEOCODER_CACHE', false),
        ],
    ];
    
  5. Integration with Laravel Requests

    use Illuminate\Http\Request;
    
    public function getUserLocation(Request $request)
    {
        $ip = $request->ip();
        $location = app(Geocoder::class)->geocode($ip)->first();
        return $location->getCoordinates();
    }
    

Advanced Patterns

  • Fallback Providers

    $geocoder->addProvider(BinaryProvider::fromPath('/path/to/db.mmdb'));
    $geocoder->addProvider(new \GeoCoder\Provider\FreeGeoIpProvider()); // Fallback
    
  • Batch Processing

    $ips = ['192.0.2.1', '198.51.100.1'];
    $results = $geocoder->geocodeBatch($ips);
    
  • Custom Data Extraction

    $location = $geocoder->geocode('1.1.1.1')->first();
    $country = $location->getCountry()->getName();
    $latitude = $location->getCoordinates()->getLatitude();
    

Gotchas and Tips

Pitfalls

  1. Database File Permissions

    • Ensure the .mmdb file is readable by the web server (e.g., chmod 644 storage/maxmind/*.mmdb).
    • Symptom: MaxMind\Exception\InvalidDatabaseException or empty results.
  2. Outdated Databases

    • MaxMind databases expire. Update them regularly (e.g., via cron or a package like spatie/laravel-maxmind).
    • Symptom: Stale or incorrect geolocation data.
  3. IPv6 Support

    • Some older MaxMind databases may not fully support IPv6. Test with ::1 (IPv6 localhost).
    • Fix: Use a recent GeoLite2/GeoIP2 database.
  4. Memory Usage

    • Large databases (e.g., GeoIP2) can consume significant memory. Optimize with caching:
      $provider->withCache(new \GeoCoder\Cache\FileCache(storage_path('cache/geocoder')));
      
  5. Time Zone Handling

    • MaxMind data includes time zones, but parsing may require additional logic:
      $timeZone = $location->getTimeZone()->getCode(); // e.g., "America/New_York"
      

Debugging Tips

  • Verify Database Validity

    use MaxMind\Db\Reader\InvalidDatabaseException;
    
    try {
        $reader = new \MaxMind\Db\Reader('/path/to/db.mmdb');
    } catch (InvalidDatabaseException $e) {
        // Log or alert: Database is corrupted or invalid.
    }
    
  • Log Queries

    $geocoder->addProvider(
        BinaryProvider::fromPath('/path/to/db.mmdb')
            ->withLogger(new \Monolog\Logger('geocoder'))
    );
    
  • Check for Empty Results

    $result = $geocoder->geocode('invalid.ip.address');
    if ($result->isEmpty()) {
        // Handle missing data (e.g., fallback to user input or default location).
    }
    

Extension Points

  1. Custom Data Mappers Override default field mappings (e.g., rename city.names.en to city_name):

    $provider = BinaryProvider::fromPath('/path/to/db.mmdb');
    $provider->setDataMapper(new \GeoCoder\Provider\MaxMind\CustomDataMapper());
    
  2. Event Listeners Extend the provider to trigger events (e.g., on cache miss):

    $provider->onCacheMiss(function ($ip) {
        // Log or trigger analytics.
    });
    
  3. Laravel Service Provider Bind the geocoder to the container for dependency injection:

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(Geocoder::class, function () {
            $geocoder = new Geocoder();
            $geocoder->addProvider(BinaryProvider::fromPath(config('geocoder.maxmind.path')));
            return $geocoder;
        });
    }
    
  4. Testing Mock the provider for unit tests:

    $mockProvider = $this->createMock(BinaryProvider::class);
    $mockProvider->method('geocode')->willReturn([new \GeoCoder\Model\Address()]);
    $geocoder->addProvider($mockProvider);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor