Weave 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

Php Maxmind Geoip Laravel Package

maxromanovsky/php-maxmind-geoip

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require maxromanovsky/php-maxmind-geoip
    
  2. First Use Case: Basic Lookup Load a MaxMind GeoIP database (e.g., GeoLite2-City.mmdb) and perform a lookup:

    use MaxMind\Db\Reader;
    
    $reader = new Reader('/path/to/GeoLite2-City.mmdb');
    $record = $reader->get($ipAddress); // e.g., '192.0.2.1'
    
    • Key Methods:
      • get($ip): Fetch record for an IP.
      • getAll($ip): Return all metadata (including deprecated fields).
      • getIncludes(): List included datasets (for composite databases).
  3. Where to Look First

    • API Docs (official MaxMind PHP API wrapper).
    • examples/ in the repo for use cases (e.g., CLI scripts, web requests).
    • tests/ for edge-case handling (e.g., invalid IPs, missing files).

Implementation Patterns

Core Workflows

  1. Web Request Integration Attach to middleware or service providers to auto-enrich requests:

    // app/Http/Middleware/GeoIpMiddleware.php
    public function handle($request, Closure $next) {
        $ip = $request->ip();
        $geoData = app(GeoIpService::class)->lookup($ip);
        $request->merge(['geo' => $geoData]);
        return $next($request);
    }
    
  2. Caching Strategies Cache responses for performance (e.g., 24-hour TTL for static IPs):

    $cacheKey = "geoip:{$ip}";
    $geoData = Cache::remember($cacheKey, now()->addHours(24), function() use ($reader, $ip) {
        return $reader->get($ip);
    });
    
  3. Composite Databases Use getIncludes() to merge multiple datasets (e.g., City + ISP):

    $reader = new Reader('/path/to/composite.mmdb');
    $includes = $reader->getIncludes();
    foreach ($includes as $include) {
        $data[$include->getName()] = $reader->get($ip, $include->getName());
    }
    
  4. Bulk Lookups Process batches (e.g., for analytics):

    $ips = ['192.0.2.1', '198.51.100.2'];
    $results = collect($ips)->map(fn($ip) => $reader->get($ip));
    

Integration Tips

  • Laravel Service Provider: Bind the Reader instance for dependency injection:
    $this->app->singleton(Reader::class, function ($app) {
        return new Reader(storage_path('app/GeoLite2-City.mmdb'));
    });
    
  • Validation: Use Laravel’s ValidatesWhenResolved to ensure the database file exists:
    public function resolveRouteBinding($ip, $reader) {
        if (!file_exists($reader->getPath())) {
            abort(500, 'GeoIP database missing');
        }
    }
    
  • Environment Awareness: Load different databases per environment (e.g., config/geoip.php):
    $path = config('geoip.database_path');
    $reader = new Reader($path);
    

Gotchas and Tips

Pitfalls

  1. Database File Permissions

    • Issue: Reader throws MaxMind\Exception\InvalidDatabaseException if the file is unreadable.
    • Fix: Ensure the web server user (e.g., www-data) has read access:
      chmod 644 /path/to/database.mmdb
      chown www-data:www-data /path/to/database.mmdb
      
  2. IPv6 Handling

    • Issue: Some older databases may not support IPv6.
    • Fix: Use Reader::withFeatures(Reader::FEATURE_IPV6) if needed:
      $reader = Reader::open($path, Reader::MODE_MEMORY, Reader::FEATURE_IPV6);
      
  3. Memory Usage

    • Issue: Large databases (e.g., GeoLite2-City.mmdb) consume ~50MB+ RAM when loaded.
    • Fix: Use Reader::MODE_FILE for disk-based lookups:
      $reader = Reader::open($path, Reader::MODE_FILE);
      
  4. Deprecated Fields

    • Issue: get() returns only "current" fields; use getAll() for legacy fields (e.g., country_code3).
    • Fix: Explicitly map deprecated fields if migrating from older APIs.
  5. Time Zone Data

    • Issue: Time zone data (e.g., time_zone) may be incomplete or outdated.
    • Fix: Supplement with a dedicated time zone database (e.g., PHP TimeZoneDB).

Debugging

  • Validate Database Integrity: Use MaxMind’s mminfo tool to check the database:
    mminfo /path/to/database.mmdb
    
  • Log Missing Records: Wrap lookups in a try-catch to log invalid IPs:
    try {
        $record = $reader->get($ip);
    } catch (\MaxMind\Exception\InvalidIpAddressException $e) {
        Log::warning("Invalid IP: {$ip}");
    }
    

Extension Points

  1. Custom Metadata Extend the Reader to add application-specific logic:

    class ExtendedReader extends Reader {
        public function getCountryName($ip) {
            $record = $this->get($ip);
            return $record['country']['names']['en'] ?? 'Unknown';
        }
    }
    
  2. Database Updates Automate updates via a Laravel command:

    // app/Console/Commands/UpdateGeoIpDatabase.php
    public function handle() {
        $this->downloadFromMaxMind();
        $this->replaceDatabaseFile();
    }
    
  3. Fallback Logic Implement fallback databases (e.g., local cache if MaxMind API fails):

    try {
        return $reader->get($ip);
    } catch (\Exception $e) {
        return $this->fallbackReader->get($ip);
    }
    
  4. Testing Mock the Reader in unit tests:

    $mockReader = Mockery::mock(Reader::class);
    $mockReader->shouldReceive('get')
               ->with('192.0.2.1')
               ->andReturn(['country' => 'US']);
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style