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

Iplocator Laravel Package

bytes4sale/iplocator

Laravel package to look up IP address details like location, currency, and language via supported providers (IPDATA, IPSTACK, IP-API). Configure API source and keys in .env, then fetch enriched IP info quickly in your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bytes4sale/iplocator
    

    Register the service provider in config/app.php (if not auto-discovered):

    'providers' => [
        Bytes4Sale\Iplocator\IplocatorServiceProvider::class,
    ],
    
  2. Basic Usage Fetch IP details via the facade:

    use Bytes4Sale\Iplocator\Facades\Iplocator;
    
    $ipDetails = Iplocator::get('8.8.8.8');
    dd($ipDetails);
    

    Expected output:

    {
      "ip": "8.8.8.8",
      "country": "United States",
      "region": "California",
      "city": "Mountain View",
      "zip": "94043",
      "latitude": 37.4056,
      "longitude": -122.0775,
      "isp": "Google LLC",
      "org": "Google Cloud Platform"
    }
    
  3. Configuration Check config/iplocator.php for API key setup (default: ip-api.com free tier).

    'api_key' => env('IPLOCATOR_API_KEY'),
    'provider' => env('IPLOCATOR_PROVIDER', 'ip-api'),
    

Implementation Patterns

Common Workflows

  1. User IP Detection

    $userIp = request()->ip();
    $location = Iplocator::get($userIp);
    

    Store in session for multi-request consistency:

    session(['user_location' => $location]);
    
  2. Geotargeted Content

    $country = Iplocator::get(request()->ip())->country;
    return view('welcome')->with('country', $country);
    
  3. Bulk IP Lookup

    $ips = ['1.1.1.1', '8.8.8.8'];
    $results = Iplocator::batch($ips);
    // Returns array of IP detail objects
    
  4. Middleware for Location-Based Logic

    namespace App\Http\Middleware;
    
    use Bytes4Sale\Iplocator\Facades\Iplocator;
    
    class CheckLocation
    {
        public function handle($request, Closure $next)
        {
            $location = Iplocator::get($request->ip());
            if ($location->country !== 'United States') {
                abort(403, 'Access denied');
            }
            return $next($request);
        }
    }
    

Integration Tips

  • Caching: Cache results for 24h to reduce API calls:
    $location = Cache::remember("ip_{$ip}", now()->addHours(24), function() use ($ip) {
        return Iplocator::get($ip);
    });
    
  • Fallback Providers: Configure multiple providers in config/iplocator.php:
    'providers' => [
        'ip-api' => [
            'url' => 'http://ip-api.com/json/{ip}',
            'key' => null,
        ],
        'ipinfo' => [
            'url' => 'https://ipinfo.io/{ip}/json',
            'key' => env('IPINFO_TOKEN'),
        ],
    ],
    
    Then use:
    Iplocator::setProvider('ipinfo')->get($ip);
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • Free tier of ip-api.com allows 45 requests/minute from an IP.
    • Solution: Implement exponential backoff or use a paid plan for production.
    • Example:
      try {
          $location = Iplocator::get($ip);
      } catch (\Bytes4Sale\Iplocator\Exceptions\RateLimitException $e) {
          sleep(60); // Wait 1 minute
          retry();
      }
      
  2. IPv6 Support

    • The package defaults to ip-api.com, which does not fully support IPv6.
    • Solution: Use ipinfo.io (configured as a fallback provider) for IPv6:
      Iplocator::setProvider('ipinfo')->get('2001:0db8:85a3::8a2e:0370:7334');
      
  3. Inconsistent Data

    • Free providers may return null for fields like zip or org.
    • Solution: Validate responses:
      $location = Iplocator::get($ip);
      $city = $location->city ?? 'Unknown';
      
  4. API Key Leaks

    • Hardcoding API keys in config/iplocator.php exposes them.
    • Solution: Use Laravel's .env and restrict file permissions:
      chmod 600 .env
      

Debugging

  • Enable Logging Set debug to true in config/iplocator.php to log API responses:

    'debug' => env('APP_DEBUG', false),
    

    Check logs at storage/logs/laravel.log.

  • Mocking for Tests Use the mock() method to simulate API responses:

    Iplocator::mock([
        'ip' => '8.8.8.8',
        'country' => 'Testland',
    ]);
    $location = Iplocator::get('8.8.8.8');
    $this->assertEquals('Testland', $location->country);
    

Extension Points

  1. Custom Fields Extend the Location model by publishing config:

    php artisan vendor:publish --provider="Bytes4Sale\Iplocator\IplocatorServiceProvider" --tag="config"
    

    Add fields to config/iplocator.php under mapping:

    'mapping' => [
        'ip' => 'ip',
        'country' => 'country',
        'custom_field' => 'raw.data.custom_key', // Access nested JSON
    ],
    
  2. Provider Extensions Create a custom provider by implementing Bytes4Sale\Iplocator\Contracts\Provider:

    namespace App\Providers;
    
    use Bytes4Sale\Iplocator\Contracts\Provider;
    
    class CustomProvider implements Provider
    {
        public function get($ip)
        {
            $response = Http::get("https://custom-api.com/{$ip}");
            return $response->json();
        }
    }
    

    Register it in config/iplocator.php:

    'providers' => [
        'custom' => App\Providers\CustomProvider::class,
    ],
    
  3. Event Listeners Listen for ip.located events to log or process locations:

    namespace App\Listeners;
    
    use Bytes4Sale\Iplocator\Events\IpLocated;
    
    class LogLocation
    {
        public function handle(IpLocated $event)
        {
            \Log::info('IP located', $event->location->toArray());
        }
    }
    

    Register in EventServiceProvider:

    protected $listen = [
        \Bytes4Sale\Iplocator\Events\IpLocated::class => [
            \App\Listeners\LogLocation::class,
        ],
    ];
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle