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

Sypex Geo Laravel Package

yamilovs/sypex-geo

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require yamilovs/sypex-geo
    

    Ensure SxGeoCity.dat (or other Sypex Geo databases) is downloaded from Sypex Geo and placed in your project (e.g., database/ or storage/).

  2. First Use Case: Locate a visitor’s city by IP in a Laravel route or controller:

    use Yamilovs\SypexGeo\SypexGeo;
    use Yamilovs\SypexGeo\Database\Mode;
    
    $sypexGeo = new SypexGeo(storage_path('app/SxGeoCity.dat'), Mode::FILE);
    $ip = request()->ip();
    $city = $sypexGeo->getCity($ip);
    return response()->json(['city' => $city->name]);
    
  3. Where to Look First:


Implementation Patterns

Core Workflows

  1. Service Provider Integration: Bind the package as a singleton in AppServiceProvider for dependency injection:

    public function register()
    {
        $this->app->singleton(SypexGeo::class, function ($app) {
            return new SypexGeo(storage_path('app/SxGeoCity.dat'), Mode::FILE);
        });
    }
    

    Inject into controllers:

    public function __construct(private SypexGeo $sypexGeo) {}
    
  2. Caching Responses: Cache geo lookups to avoid repeated disk I/O (e.g., using Laravel’s cache):

    public function getCachedCity(string $ip): ?array
    {
        return cache()->remember("geo.city.$ip", now()->addHours(1), function () use ($ip) {
            return $this->sypexGeo->getCity($ip)?->toArray();
        });
    }
    
  3. Multi-Database Lookups: Chain multiple databases (e.g., country + city) for richer data:

    $country = $sypexGeoCountry->getCountry($ip);
    $city = $sypexGeoCity->getCity($ip);
    return ['country' => $country->name, 'city' => $city->name];
    
  4. Middleware for Geo-Aware Routes: Attach middleware to enrich requests with geo data:

    public function handle(Request $request, Closure $next)
    {
        $request->merge(['geo' => $this->sypexGeo->getCity($request->ip())]);
        return $next($request);
    }
    

    Access in routes/controllers:

    $city = request()->geo->name;
    
  5. Command for Database Updates: Create an Artisan command to auto-update databases (if needed):

    use Illuminate\Console\Command;
    
    class UpdateGeoDatabase extends Command
    {
        protected $signature = 'geo:update';
        public function handle()
        {
            // Download latest SxGeoCity.dat and replace old file
        }
    }
    

Gotchas and Tips

Pitfalls

  1. File Paths:

    • Issue: Hardcoded paths (e.g., __DIR__.'/SxGeoCity.dat') break in shared hosting or Docker.
    • Fix: Use Laravel’s storage_path() or config:
      config(['sypexgeo.path' => storage_path('app/SxGeoCity.dat')]);
      
  2. Database Updates:

    • Issue: Sypex Geo databases require manual updates (no built-in auto-update).
    • Fix: Schedule a cron job or use the Artisan command pattern above.
  3. Memory Usage:

    • Issue: Large databases (e.g., SxGeoCountry.dat) may cause high memory usage.
    • Fix: Use Mode::MEMORY_MAPPED for better performance:
      $sypexGeo = new SypexGeo($path, Mode::MEMORY_MAPPED);
      
  4. IPv6 Support:

    • Issue: Sypex Geo primarily supports IPv4. IPv6 may return null.
    • Fix: Normalize IPs (e.g., use filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)).
  5. Case Sensitivity:

    • Issue: Database keys may be case-sensitive in some environments.
    • Fix: Normalize IP strings (e.g., strtolower()).

Debugging

  • Verify Database Integrity: Check if the .dat file is corrupted by testing with a known IP (e.g., Google’s IP):
    $sypexGeo->getCity('142.250.190.46'); // Should return Mountain View, USA
    
  • Log Missing Data: Wrap calls in try-catch to log failures:
    try {
        $city = $sypexGeo->getCity($ip);
    } catch (\Exception $e) {
        Log::error("Geo lookup failed for IP $ip: " . $e->getMessage());
    }
    

Extension Points

  1. Custom Data Models: Extend the City class to add fields (e.g., latitude, longitude):

    class ExtendedCity extends \Yamilovs\SypexGeo\City
    {
        public function getCoordinates(): array
        {
            return [$this->latitude, $this->longitude];
        }
    }
    

    Override the getCity() method to return your extended class.

  2. Bulk Lookups: For performance, process IPs in batches (e.g., using queues):

    GeoLookupJob::dispatch($ip)->delay(now()->addSeconds(5));
    
  3. Fallback Logic: Implement fallback to a free API (e.g., ipapi.co) if Sypex Geo fails:

    public function getCityWithFallback(string $ip)
    {
        $city = $this->sypexGeo->getCity($ip);
        return $city ?: $this->fetchFromIpApi($ip);
    }
    
  4. Testing: Mock the SypexGeo class in tests:

    $mock = Mockery::mock(SypexGeo::class);
    $mock->shouldReceive('getCity')->andReturn((object) ['name' => 'Test City']);
    $this->app->instance(SypexGeo::class, $mock);
    
  5. Configuration: Centralize paths and modes in config/sypexgeo.php:

    return [
        'path' => storage_path('app/SxGeoCity.dat'),
        'mode' => \Yamilovs\SypexGeo\Database\Mode::MEMORY_MAPPED,
    ];
    

    Access via config('sypexgeo.path').

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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope