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 Geo Base Laravel Package

cimus/ip-geo-base

Определение страны, города, региона и координат по IP через базы ipgeobase.ru. Загружает архив, конвертирует текстовые базы в бинарный формат для быстрого поиска. Обновление данных удобно запускать по cron (например, раз в неделю).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cimus/ip-geo-base
    

    Add the service provider to config/app.php under providers:

    Cimus\IpGeoBase\IpGeoBaseServiceProvider::class,
    
  2. Basic Usage Fetch geolocation data for an IP address:

    use Cimus\IpGeoBase\Facades\IpGeoBase;
    
    $ip = '8.8.8.8';
    $data = IpGeoBase::get($ip);
    
    // Outputs structured data like:
    // [
    //   'country' => 'US',
    //   'region' => 'CA',
    //   'city' => 'Mountain View',
    //   ...
    // ]
    
  3. First Use Case

    • Geo-blocking: Check if a user’s IP belongs to a restricted country.
    $ip = request()->ip();
    $country = IpGeoBase::get($ip)['country'];
    if ($country === 'CN') {
        abort(403, 'Access denied for Chinese IPs.');
    }
    

Implementation Patterns

Common Workflows

  1. Caching Responses Cache results for performance (e.g., 1 hour for static data):

    $data = Cache::remember("ip_geo_{$ip}", now()->addHour(), function () use ($ip) {
        return IpGeoBase::get($ip);
    });
    
  2. Bulk IP Lookup Process multiple IPs efficiently (e.g., for analytics):

    $ips = ['1.1.1.1', '8.8.8.8', '203.0.113.45'];
    $results = collect($ips)->map(fn($ip) => IpGeoBase::get($ip));
    
  3. Integration with Middleware Attach geolocation data to requests globally:

    namespace App\Http\Middleware;
    
    use Closure;
    use Cimus\IpGeoBase\Facades\IpGeoBase;
    
    class GeoMiddleware
    {
        public function handle($request, Closure $next)
        {
            $request->merge(['geo' => IpGeoBase::get($request->ip())]);
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        \App\Http\Middleware\GeoMiddleware::class,
    ];
    
  4. Laravel Blade Directives Access geodata in views:

    // In a Blade component
    @geo('country')
    @geo('city')
    

    Add to AppServiceProvider:

    Blade::directive('geo', function ($field) {
        return "<?php echo request()->geo['{$field}'] ?? 'N/A'; ?>";
    });
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • The free tier of the underlying service (e.g., IP-API) may throttle requests. Implement retries or fallback logic:
    try {
        $data = IpGeoBase::get($ip);
    } catch (\Exception $e) {
        $data = Cache::get("ip_geo_fallback_{$ip}", []);
    }
    
  2. IPv6 Support

    • Test with IPv6 addresses (e.g., 2001:0db8::1). The package may require manual validation:
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        // Handle IPv6-specific logic
    }
    
  3. Data Accuracy

    • Free geolocation databases (e.g., MaxMind GeoLite) are less accurate. For production, consider paid alternatives or supplement with user-provided data.
  4. Configuration Quirks

    • The package may rely on environment variables (e.g., IPGEOBASE_API_KEY). Ensure these are set in .env:
    IPGEOBASE_API_KEY=your_api_key_here
    

Debugging

  • Log Raw Responses Inspect the raw API response for debugging:

    $raw = IpGeoBase::raw($ip);
    \Log::debug('Geo API Response', ['data' => $raw]);
    
  • Fallback to Local Database Cache a local copy of the geolocation database (e.g., MaxMind MMDB) for offline use:

    $geo = IpGeoBase::get($ip, ['use_local_db' => true]);
    

Extension Points

  1. Custom Data Fields Extend the response structure by overriding the service:

    IpGeoBase::extend(function ($data) {
        $data['is_eu'] = in_array($data['country'], ['DE', 'FR', 'IT', 'ES', 'PT']);
        return $data;
    });
    
  2. Proxy Support Configure the package to work behind proxies:

    IpGeoBase::setProxy('http://proxy.example.com:8080');
    
  3. Testing Mock geolocation data in tests:

    IpGeoBase::shouldReceive('get')->andReturn([
        'country' => 'US',
        'city' => 'Testville',
    ]);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui