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

Ip Info Db Provider Laravel Package

geocoder-php/ip-info-db-provider

IP-Info-DB provider for PHP-GeoCoder (Geocoder PHP). Look up IP address geolocation via the ipinfodb.com API and return standardized Geocoder results. Useful for adding country/region/city data to apps from an IP.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require geocoder-php/ip-info-db-provider
    

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

  2. Basic Usage

    use Geocoder\Geocoder;
    use Geocoder\Provider\IpInfoDb\IpInfoDbProvider;
    
    $geocoder = new Geocoder();
    $geocoder->registerProvider(new IpInfoDbProvider());
    
    $ip = '8.8.8.8';
    $result = $geocoder->geocode($ip);
    dd($result->getCoordinates()); // Returns [lat, lng]
    
  3. First Use Case

    • Fetch geolocation data for a user’s IP (e.g., in a middleware or controller):
      $ip = request()->ip();
      $location = $geocoder->geocode($ip)->first();
      $city = $location->getCity();
      

Implementation Patterns

Common Workflows

  1. Middleware for IP-Based Geo-Lookup

    namespace App\Http\Middleware;
    
    use Closure;
    use Geocoder\Geocoder;
    
    class GeoMiddleware
    {
        protected $geocoder;
    
        public function __construct(Geocoder $geocoder)
        {
            $this->geocoder = $geocoder;
        }
    
        public function handle($request, Closure $next)
        {
            $ip = $request->ip();
            $location = $this->geocoder->geocode($ip)->first();
            $request->merge(['geo' => $location]);
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\GeoMiddleware::class,
    ];
    
  2. Caching Results Use Laravel’s cache to avoid repeated API calls for the same IP:

    $cacheKey = "ip_geo_{$ip}";
    $location = cache()->remember($cacheKey, now()->addHours(1), function () use ($geocoder, $ip) {
        return $geocoder->geocode($ip)->first();
    });
    
  3. Bulk IP Lookup For multiple IPs (e.g., in a report), batch requests:

    $ips = ['1.1.1.1', '2.2.2.2'];
    $results = collect($ips)->map(function ($ip) use ($geocoder) {
        return $geocoder->geocode($ip)->first();
    });
    

Integration Tips

  • Laravel Service Provider Bind the provider to the container for dependency injection:

    $this->app->bind(IpInfoDbProvider::class, function ($app) {
        return new IpInfoDbProvider($app['config']['services.ipinfodb']);
    });
    

    Configure in config/services.php:

    'ipinfodb' => [
        'api_key' => env('IPINFO_DB_API_KEY'),
        'database' => env('IPINFO_DB_DATABASE', 'IPINFO_DB_LITE'),
    ],
    
  • Eloquent Observers Auto-populate city, country, or latitude fields on model creation:

    class UserObserver
    {
        public function creating(User $user)
        {
            $ip = request()->ip();
            $location = $geocoder->geocode($ip)->first();
            $user->city = $location->getCity();
            $user->country = $location->getCountry();
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • The provider uses a local database (no external API calls), but ensure your database is up-to-date. Outdated data may return stale results.
    • Fix: Periodically update the database (e.g., via a cron job or artisan command).
  2. Database Size

    • The full IPINFO_DB database (~100MB) may bloat your project. Use IPINFO_DB_LITE (~10MB) for lightweight needs.
    • Tip: Store the database file outside the Laravel root (e.g., /var/ipinfo_db) and symlink it to storage/.
  3. IPv6 Support

    • Limited IPv6 coverage in the database. Test thoroughly if your audience uses IPv6.
    • Workaround: Fallback to another provider (e.g., MaxMind) for IPv6 IPs.
  4. Time Zone Data

    • The provider does not return time zones. Use a separate library (e.g., overtrue/geoip) if needed.
  5. Case Sensitivity

    • Country codes (e.g., US vs us) may vary. Normalize with strtoupper():
      $country = strtoupper($location->getCountry());
      

Debugging

  • Verify Database Path Ensure the config points to the correct .mmdb file:

    $provider = new IpInfoDbProvider([
        'database' => storage_path('app/ipinfo_db/IPINFO_DB_LITE.mmdb'),
    ]);
    

    Throw an exception if the file is missing:

    if (!file_exists($databasePath)) {
        throw new \RuntimeException("IPInfoDB database not found at {$databasePath}");
    }
    
  • Check IP Format Invalid IPs (e.g., 256.0.0.1) will return null. Validate with:

    if (filter_var($ip, FILTER_VALIDATE_IP)) {
        $location = $geocoder->geocode($ip)->first();
    }
    

Extension Points

  1. Custom Fields Extend the provider to return additional data (e.g., ISP) by parsing the raw database response:

    class CustomIpInfoDbProvider extends IpInfoDbProvider
    {
        public function getIsp($ip)
        {
            $data = $this->getData($ip);
            return $data['traits']['isp'] ?? null;
        }
    }
    
  2. Fallback Providers Combine with other providers for redundancy:

    $geocoder->registerProvider(new IpInfoDbProvider());
    $geocoder->registerProvider(new MaxMindProvider());
    $location = $geocoder->geocode($ip)->first(); // Tries both
    
  3. Artisan Command for Updates Create a command to auto-update the database:

    use Symfony\Component\Process\Process;
    
    class UpdateIpInfoDbCommand extends Command
    {
        protected $signature = 'ipinfo:update';
        protected $description = 'Download the latest IPInfoDB database';
    
        public function handle()
        {
            $process = new Process(['wget', 'https://example.com/ipinfo_db/IPINFO_DB_LITE.mmdb', '-O', storage_path('app/ipinfo_db/IPINFO_DB_LITE.mmdb')]);
            $process->run();
            $this->info($process->getOutput());
        }
    }
    
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.
terminal42/code-quality-tools
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