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 Id Cities Laravel Package

ferdirn/laravel-id-cities

Laravel package to create and seed an Indonesian cities (kota/kabupaten) table. Includes artisan commands to generate migrations and a seeder, plus optional config for table naming. Provides Cities service provider, facade, and ready-to-use city data.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ferdirn/laravel-id-cities:dev-master
    

    Update config/app.php:

    'providers' => [
        Ferdirn\Cities\CitiesServiceProvider::class,
    ],
    'aliases' => [
        'Cities' => Ferdirn\Cities\CitiesFacade::class,
    ],
    
  2. Publish Migrations:

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

    Run migrations:

    php artisan migrate
    
  3. First Use Case: Fetch all Indonesian cities via the facade:

    $cities = Cities::all();
    

    Or retrieve a single city by ID:

    $city = Cities::find(1);
    

Implementation Patterns

Core Workflows

  1. Data Retrieval:

    • Facade Methods:
      // Get all cities
      $allCities = Cities::all();
      
      // Find by ID
      $city = Cities::find(1);
      
      // Get by province (if linked)
      $jakartaCities = Cities::where('province_id', 31)->get();
      
    • Eloquent Model: Use the City model directly for query building:
      use Ferdirn\Cities\Models\City;
      
      $cities = City::where('name', 'like', '%Jakarta%')->get();
      
  2. Integration with Forms:

    • Use the package for dropdowns or autocomplete fields:
      $provinces = Cities::getProvinces(); // If extended
      $cities = Cities::where('province_id', $selectedProvince)->get();
      
    • Pair with laravelcollective/html for form helpers:
      <select name="city_id">
          @foreach(Cities::all() as $city)
              <option value="{{ $city->id }}">{{ $city->name }}</option>
          @endforeach
      </select>
      
  3. API Responses:

    • Return cities as JSON in controllers:
      return response()->json(Cities::all());
      
    • Filter by province for API endpoints:
      return Cities::where('province_id', request('province_id'))->get();
      
  4. Seeding:

    • Pre-populate the cities table during deployment:
      php artisan db:seed --class=CitiesTableSeeder
      
    • Extend the seeder if custom logic is needed.

Advanced Patterns

  1. Relationships:

    • Link cities to provinces or regions (if the package supports it):
      // Example: Assume `City` has a `province()` relationship
      $cityWithProvince = City::with('province')->find(1);
      
    • Use polymorphic relationships for flexible associations:
      // Example: Attach cities to a `Location` model
      public function cities()
      {
          return $this->morphToMany(City::class, 'cityable');
      }
      
  2. Caching:

    • Cache city lists to reduce database load:
      $cities = Cache::remember('all_cities', now()->addHours(1), function () {
          return Cities::all();
      });
      
  3. Localization:

    • Override city names or add translations:
      // Extend the City model
      class City extends \Ferdirn\Cities\Models\City
      {
          public function getNameAttribute($value)
          {
              return __($value); // Use Laravel's translation system
          }
      }
      
  4. Validation:

    • Use the package for form validation:
      use App\Rules\ValidCity;
      
      $request->validate([
          'city_id' => ['required', new ValidCity],
      ]);
      
    • Create a custom rule:
      class ValidCity implements \Illuminate\Contracts\Validation\Rule
      {
          public function passes($attribute, $value)
          {
              return Cities::find($value) !== null;
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • If you’ve manually created a cities table, drop it first before publishing migrations to avoid conflicts.
    • Check for column name mismatches (e.g., city_name vs. name).
  2. Dev-Master Dependency:

    • The package uses dev-master, which may introduce breaking changes. Pin a specific version if stability is critical:
      composer require ferdirn/laravel-id-cities:1.0.0
      
  3. Missing Relationships:

    • The package may not include province/country relationships by default. Manually define them in the City model:
      public function province()
      {
          return $this->belongsTo(Province::class);
      }
      
  4. Performance:

    • Fetching all cities (Cities::all()) can be slow. Use pagination or lazy loading:
      $cities = Cities::paginate(20);
      
    • Avoid eager loading unnecessary relationships if not needed.
  5. Facade vs. Model:

    • The facade (Cities::) and model (City::) are interchangeable, but the facade may not support all Eloquent methods. Prefer the model for complex queries.

Debugging

  1. Data Integrity:

  2. Missing Cities:

    • If a city is missing, check if the package’s data is outdated. Consider contributing an update or extending the data source.
  3. SQL Errors:

    • Ensure the cities table exists and matches the expected schema. Run:
      php artisan schema:dump
      
      to inspect the table structure.

Tips

  1. Extend the Package:

    • Override the City model to add custom methods:
      class City extends \Ferdirn\Cities\Models\City
      {
          public function isCapital()
          {
              return $this->name === 'Jakarta';
          }
      }
      
  2. Testing:

    • Mock the City model in tests:
      $city = City::factory()->create(['name' => 'Bandung']);
      
    • Use RefreshDatabase trait for migration testing.
  3. Documentation:

    • Since the package is minimal, document custom usage in your project’s README (e.g., "Cities are linked to provinces via province_id").
  4. Alternatives:

    • For broader coverage, combine with ferdirn/laravel-id-provinces and ferdirn/laravel-id-countries for a full geographic hierarchy.
  5. Local Development:

    • Use php artisan tinker to explore city data interactively:
      php artisan tinker
      >>> Cities::where('name', 'like', '%Surabaya%')->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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui