cimus/ip-geo-base
Определение страны, города, региона и координат по IP через базы ipgeobase.ru. Загружает архив, конвертирует текстовые базы в бинарный формат для быстрого поиска. Обновление данных удобно запускать по cron (например, раз в неделю).
Installation
composer require cimus/ip-geo-base
Add the service provider to config/app.php under providers:
Cimus\IpGeoBase\IpGeoBaseServiceProvider::class,
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',
// ...
// ]
First Use Case
$ip = request()->ip();
$country = IpGeoBase::get($ip)['country'];
if ($country === 'CN') {
abort(403, 'Access denied for Chinese IPs.');
}
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);
});
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));
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,
];
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'; ?>";
});
Rate Limiting
try {
$data = IpGeoBase::get($ip);
} catch (\Exception $e) {
$data = Cache::get("ip_geo_fallback_{$ip}", []);
}
IPv6 Support
2001:0db8::1). The package may require manual validation:if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
// Handle IPv6-specific logic
}
Data Accuracy
Configuration Quirks
IPGEOBASE_API_KEY). Ensure these are set in .env:IPGEOBASE_API_KEY=your_api_key_here
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]);
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;
});
Proxy Support Configure the package to work behind proxies:
IpGeoBase::setProxy('http://proxy.example.com:8080');
Testing Mock geolocation data in tests:
IpGeoBase::shouldReceive('get')->andReturn([
'country' => 'US',
'city' => 'Testville',
]);
How can I help you explore Laravel packages today?