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.
Installation Add the package via Composer:
composer require geocoder-php/host-ip-provider
Ensure geocoder-php/geocoder is also installed (this provider extends it).
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);
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);
}
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);
};
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();
});
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]);
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();
}
}
Geocoder instance for dependency injection:
$this->app->singleton(Geocoder::class, function ($app) {
$geocoder = new Geocoder();
$geocoder->registerProvider(new HostIpProvider());
return $geocoder;
});
Resource classes):
class GeoDataResource extends JsonResource {
public function toArray($request) {
return [
'latitude' => $this->getLatitude(),
'longitude' => $this->getLongitude(),
'country' => $this->getCountry()->getName(),
];
}
}
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;
}
IPv6 Support
Ensure your server and Laravel app handle IPv6 addresses (e.g., request()->ip() returns the correct format).
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}");
}
Configuration Quirks The provider may require no additional config, but check for:
$provider = $geocoder->provider('host_ip');
$rawData = $provider->getHttpClient()->get($provider->getUrl($ip));
Log::debug("Raw geocode response: " . $rawData);
8.8.8.8) to verify provider behavior.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');
}
}
Post-Processing Transform results before storage (e.g., extract city from a nested array):
$location = $geocoder->geocode($ip)->first();
$city = $location->getData()['city'] ?? null;
Event Dispatching
Trigger events for geocoding results (e.g., Geocoded):
event(new Geocoded($ip, $location));
How can I help you explore Laravel packages today?