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

Laravel Cities Laravel Package

ijeffro/laravel-cities

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ijeffro/laravel-cities
    

    For Laravel 5.x, use dev-master as specified in the README.

  2. Register Service Provider & Facade: Add to config/app.php:

    'providers' => [
        ijeffro\Cities\CitiesServiceProvider::class,
    ],
    'aliases' => [
        'Cities' => ijeffro\Cities\CitiesFacade::class,
    ],
    
  3. Publish Migrations (if needed): Run:

    php artisan vendor:publish --provider="ijeffro\Cities\CitiesServiceProvider" --tag=migrations
    

    Then migrate:

    php artisan migrate
    
  4. First Use Case: Fetch a city by IATA code:

    $city = Cities::findByIata('JFK');
    // Returns: ['name' => 'New York', 'country_code' => 'US', ...]
    

Implementation Patterns

Core Workflows

  1. Querying Cities:

    • By IATA Code:
      $city = Cities::findByIata('LAX'); // Los Angeles
      
    • By Name (Partial Match):
      $cities = Cities::findByName('Paris');
      
    • By Country Code:
      $citiesInFrance = Cities::findByCountry('FR');
      
  2. Integration with Eloquent Models: Add a relationship to a User model (e.g., for storing preferred cities):

    public function preferredCity()
    {
        return $this->belongsTo(City::class, 'city_id');
    }
    

    Use the facade to fetch cities dynamically:

    $user->preferredCity = Cities::findByIata($request->iata_code);
    
  3. Validation: Validate IATA codes in forms:

    $validator = Validator::make($request->all(), [
        'iata_code' => 'required|exists:cities,iata_code',
    ]);
    
  4. API Responses: Return city data in API endpoints:

    return response()->json(Cities::findByIata($request->iata));
    

Advanced Patterns

  1. Custom Queries: Extend the facade or use the underlying repository:

    $cities = Cities::repository()->where('country_code', 'US')->get();
    
  2. Caching: Cache frequent queries (e.g., country dropdowns):

    $countries = Cache::remember('countries', 60, function () {
        return Cities::getCountries();
    });
    
  3. Localization: Translate city names dynamically:

    $city = Cities::findByIata('CDG');
    $translatedName = __($city['name']);
    
  4. Seeding: Use the package to seed cities in a database:

    Cities::all()->each(function ($city) {
        City::firstOrCreate(['iata_code' => $city['iata_code']], $city);
    });
    

Gotchas and Tips

Pitfalls

  1. Laravel Version Mismatch:

    • The dev-master branch is Laravel 5.x only. For Laravel 8/9/10, check for updated forks or alternatives like spatie/laravel-cities.
    • Fix: Use a compatible fork or manually adapt the package.
  2. Missing Migrations:

    • If migrations aren’t published, the cities table won’t exist.
    • Fix: Run php artisan vendor:publish --tag=migrations and migrate.
  3. Case Sensitivity:

    • IATA codes are case-sensitive in queries (e.g., 'JFK''jfk').
    • Fix: Normalize input:
      $city = Cities::findByIata(strtoupper($request->iata));
      
  4. Data Inconsistencies:

    • The dataset may not cover all cities or may have duplicates.
    • Fix: Validate data before use or extend the package with custom logic.

Debugging Tips

  1. Check Database: Verify the cities table exists and has data:

    php artisan tinker
    >>> \DB::table('cities')->count();
    
  2. Facade vs. Repository:

    • Use Cities::repository() for direct query access if the facade doesn’t expose needed methods.
  3. Logging: Add debug logs for missing cities:

    $city = Cities::findByIata('XYZ');
    if (!$city) {
        \Log::warning("IATA code 'XYZ' not found in cities database.");
    }
    

Extension Points

  1. Custom Fields: Add columns to the cities table (e.g., timezone, population) and extend the model:

    // In a service provider:
    Cities::extend(function ($app) {
        $app->bind('city.model', function () {
            return new App\Models\ExtendedCity();
        });
    });
    
  2. Override Queries: Replace the default repository with a custom implementation:

    // In a service provider:
    Cities::repository(function () {
        return new App\Repositories\CustomCityRepository();
    });
    
  3. Add New Data Sources: Merge with external APIs (e.g., Google Places) by extending the facade:

    Cities::extend(function () {
        return new App\Services\HybridCityService();
    });
    

Performance Tips

  1. Indexing: Ensure iata_code, name, and country_code are indexed in the cities table for faster lookups.

  2. Batch Fetching: Use pluck() for lightweight data:

    $iataCodes = Cities::pluck('iata_code');
    
  3. Avoid N+1 Queries: Eager-load relationships when fetching cities for models:

    $users = User::with(['preferredCity' => function ($query) {
        $query->select('id', 'name', 'iata_code');
    }])->get();
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor