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

Host Ip Provider Laravel Package

geocoder-php/host-ip-provider

HostIP provider for the PHP Geocoder library. Retrieves geolocation data for an IP address using the hostip.info service, returning standard Geocoder results. Lightweight adapter to plug HostIP into geocoder-php for quick IP-to-location lookups.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require geocoder-php/host-ip-provider
    

    Ensure geocoder-php/geocoder is also installed (this provider extends it).

  2. Basic Usage Register the provider in Laravel’s config/geocoder.php:

    'providers' => [
        'host_ip' => [
            'class' => \Geocoder\Provider\HostIp::class,
        ],
    ],
    

    Use it in a controller or service:

    use Geocoder\Geocoder;
    use Geocoder\Provider\HostIp\HostIpProvider;
    
    $geocoder = new Geocoder();
    $geocoder->registerProvider(new HostIpProvider());
    
    $ip = request()->ip(); // Or any IP string
    $result = $geocoder->geocode($ip);
    
  3. First Use Case Fetch geolocation data for a user’s IP (e.g., in a UserController):

    public function showUserLocation(Request $request) {
        $ip = $request->ip();
        $location = $geocoder->geocode($ip)->first();
        return response()->json($location);
    }
    

Implementation Patterns

Common Workflows

  1. Request-Based Geocoding Attach geolocation to incoming requests:

    $middleware = function ($request, $next) {
        $ip = $request->ip();
        $location = $geocoder->geocode($ip)->first();
        $request->merge(['geo_data' => $location]);
        return $next($request);
    };
    
  2. Caching Responses Cache results to avoid repeated API calls (e.g., using Laravel’s cache):

    $cacheKey = "geo_{$ip}";
    $location = cache()->remember($cacheKey, now()->addHours(1), function() use ($geocoder, $ip) {
        return $geocoder->geocode($ip)->first();
    });
    
  3. Fallback Providers Combine with other providers (e.g., geocoder-php/google-provider) for redundancy:

    $geocoder->registerProvider(new \Geocoder\Provider\GoogleMapsProvider('API_KEY'));
    $result = $geocoder->geocode($ip, ['provider' => 'host_ip', 'fallback' => true]);
    
  4. Model Observers Automatically update a User model’s location field:

    class UserObserver {
        public function created(User $user) {
            $ip = request()->ip();
            $user->location = $geocoder->geocode($ip)->first();
            $user->save();
        }
    }
    

Integration Tips

  • Laravel Service Container: Bind the Geocoder instance for dependency injection:
    $this->app->singleton(Geocoder::class, function ($app) {
        $geocoder = new Geocoder();
        $geocoder->registerProvider(new HostIpProvider());
        return $geocoder;
    });
    
  • API Responses: Normalize geodata into a consistent format (e.g., using Laravel’s Resource classes):
    class GeoDataResource extends JsonResource {
        public function toArray($request) {
            return [
                'latitude' => $this->getLatitude(),
                'longitude' => $this->getLongitude(),
                'country' => $this->getCountry()->getName(),
            ];
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Rate Limits The host-ip-provider may throttle requests. Implement exponential backoff or caching:

    try {
        $result = $geocoder->geocode($ip);
    } catch (\Geocoder\Exception\UnsupportedProviderException $e) {
        Log::warning("Geocoding failed for IP {$ip}: " . $e->getMessage());
        return null;
    }
    
  2. IPv6 Support Ensure your server and Laravel app handle IPv6 addresses (e.g., request()->ip() returns the correct format).

  3. Data Accuracy Free tiers of host-ip-provider may lack precision. Validate results:

    if (!$result->first()) {
        throw new \RuntimeException("No geolocation data for IP {$ip}");
    }
    
  4. Configuration Quirks The provider may require no additional config, but check for:

    • Timeouts: Set a timeout for HTTP requests (e.g., via Guzzle client).
    • User-Agent: Some providers block default user agents. Override in the provider’s HTTP client.

Debugging

  • Log Raw Responses: Inspect the raw API response for debugging:
    $provider = $geocoder->provider('host_ip');
    $rawData = $provider->getHttpClient()->get($provider->getUrl($ip));
    Log::debug("Raw geocode response: " . $rawData);
    
  • Test with Known IPs: Use static IPs (e.g., Google’s 8.8.8.8) to verify provider behavior.

Extension Points

  1. Custom Providers Extend the base HostIpProvider to add authentication or custom endpoints:

    class CustomHostIpProvider extends HostIpProvider {
        protected function getUrl($ip) {
            return "https://custom-api.com/geocode?ip={$ip}&auth=" . config('services.custom_api_key');
        }
    }
    
  2. Post-Processing Transform results before storage (e.g., extract city from a nested array):

    $location = $geocoder->geocode($ip)->first();
    $city = $location->getData()['city'] ?? null;
    
  3. Event Dispatching Trigger events for geocoding results (e.g., Geocoded):

    event(new Geocoded($ip, $location));
    
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.
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk