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 World Laravel Package

jszdavid/laravel-world

Laravel package providing countries, states, and cities data (based on nnjeim/world) with migrations, seeder, configurable table names and route prefix, optional country filters, and a World facade/API endpoints with optional query caching.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require jszd2022/laravel-world
    php artisan vendor:publish --provider="JSzD\World\WorldServiceProvider"
    php artisan migrate
    php -d memory_limit=512M artisan db:seed --class=WorldSeeder
    
    • Verify the config/laravel-world.php file exists after publishing.
  2. First Use Case: Fetch all countries with the facade:

    use JSzD\World\Facades\World;
    $countries = World::countries()->get();
    
    • Output: Collection of Country models with default fields (id, name, iso2).
  3. Where to Look First:

    • Facade: JSzD\World\Facades\World (primary entry point).
    • Config: config/laravel-world.php (customize table names, routes, or country filters).
    • Migrations: database/migrations/[timestamp]_create_laravel_world_tables.php (schema reference).

Implementation Patterns

Core Workflows

  1. Data Retrieval:

    • Countries:
      // Basic fetch
      $countries = World::countries()->get();
      
      // Filtered (e.g., by region)
      $americanCountries = World::countries()->where('region', 'Americas')->get();
      
      // Select specific fields
      $countries = World::countries()->select('name', 'iso2')->get();
      
    • States/Cities (requires country ID):
      $states = World::states()->ofCountry(1)->get(); // 1 = country ID
      $cities = World::cities()->ofState(1)->get();  // 1 = state ID
      
    • Eager Loading:
      $country = World::countries()->with('states.cities')->find(1);
      
  2. API Routes (if enabled):

    • Endpoints auto-registered under config('laravel-world.routes.prefix'):
      • GET /api/countries → All countries.
      • GET /api/countries/{id}/states → States for a country.
      • GET /api/states/{id}/cities → Cities for a state.
    • Customize routes by modifying routes/api.php or disabling in config.
  3. Caching:

    • Data cached for config('laravel-world.cache_ttl') (default: 1 week).
    • Clear cache manually:
      World::clearCache();
      
  4. Filtering Countries During Seed:

    • Use config('laravel-world.countries.only') or except to limit seeded data:
      // config/laravel-world.php
      'countries' => [
          'only' => ['US', 'CA', 'GB'], // Seed only these countries
      ],
      
    • Re-run php artisan db:seed --class=WorldSeeder after changes.

Integration Tips

  1. Eloquent Relationships: Define relationships in your models to leverage Laravel’s ORM:

    // app/Models/Country.php
    public function states()
    {
        return $this->hasMany(State::class, 'country_id');
    }
    
    • Sync with package tables via country_id foreign keys.
  2. Validation: Use the package for form validation (e.g., country/state/city selection):

    use JSzD\World\Rules\ValidCountry;
    
    $request->validate([
        'country' => ['required', new ValidCountry],
    ]);
    
  3. Localization: Extend the name field to support translations:

    // Add to migration
    Schema::table('laravel-world-countries', function (Blueprint $table) {
        $table->string('name_en')->nullable();
        $table->string('name_es')->nullable();
    });
    
    • Update seeder or manually populate translated names.
  4. Testing:

    • Use World::fake() for unit tests:
      World::fake([
          'countries' => ['US' => ['name' => 'United States']],
      ]);
      

Gotchas and Tips

Pitfalls

  1. Memory Limits:

    • Seeding all countries/states/cities requires 512MB+ memory. Increase memory_limit in php.ini if needed:
      memory_limit = 1G
      
    • For large datasets, seed incrementally or use only/except filters.
  2. Table Name Conflicts:

    • Default table names (laravel-world-*) may clash with existing tables.
    • Fix: Customize in config:
      'migrations' => [
          'countries' => ['table_name' => 'custom_countries'],
      ],
      
    • Run php artisan migrate:fresh if tables already exist.
  3. API Route Overrides:

    • Disabling routes in config ('routes.enabled' => false) does not remove the provider’s route registration.
    • Fix: Manually remove routes in routes/api.php or use middleware to block access.
  4. Cache Invalidation:

    • Changes to seeded data (e.g., manual DB updates) won’t reflect until cache expires.
    • Workaround: Clear cache or set cache_ttl to 0 for development:
      config(['laravel-world.cache_ttl' => 0]);
      
  5. ISO Codes:

    • The package uses ISO 3166-1 alpha-2 codes (e.g., US, GB). Validate inputs to avoid mismatches:
      $validCodes = World::countries()->pluck('iso2');
      

Debugging Tips

  1. Seeder Issues:

    • Check for duplicate entries or foreign key violations:
      SELECT * FROM laravel-world-states WHERE country_id NOT IN (SELECT id FROM laravel-world-countries);
      
    • Solution: Truncate tables before reseeding:
      php artisan db:seed --class=WorldSeeder --force
      
  2. Performance:

    • Query optimization: Use select() to limit fields:
      World::countries()->select('id', 'name', 'iso2')->get();
      
    • Avoid with() on large datasets (e.g., all cities for a country).
  3. Configuration Overrides:

    • Publish the config file after installation to avoid missing keys:
      php artisan vendor:publish --provider="JSzD\World\WorldServiceProvider" --tag=config
      
  4. Extension Points:

    • Add Custom Fields: Extend migrations/seeder to include additional columns (e.g., population, flag).
    • Override Models: Publish and extend the package’s models:
      php artisan vendor:publish --provider="JSzD\World\WorldServiceProvider" --tag=models
      
      • Modify app/Models/World/Country.php, etc.
  5. Logging:

    • Enable debug mode in config to log queries:
      'debug' => env('APP_DEBUG', false),
      
    • Check logs for seeder errors:
      tail -f storage/logs/laravel.log
      

Pro Tips

  1. Partial Seeding:

    • Seed only specific countries/states for testing:
      php artisan db:seed --class=WorldSeeder --only=US,CA
      
  2. Dynamic Data:

    • Fetch data on-demand (e.g., for a dropdown) without caching:
      World::countries()->uncached()->get();
      
  3. Geocoding Integration:

    • Combine with spatie/laravel-geocoder for location-based features:
      $city = World::cities()->find(1);
      $coordinates = geoCode($city->name);
      
  4. Soft Deletes:

    • Enable soft deletes in migrations for flexible data management:
      $table->softDeletes();
      
    • Use withTrashed() to include "deleted" records.
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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