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

World Laravel Package

eka/world

Laravel package providing a comprehensive world database: countries, states, cities, timezones, currencies, and languages. Query via a World facade or ready-made API routes, with filtering and eager-loaded related data (e.g., states/cities by country).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Installation

    composer require eka/world
    php artisan vendor:publish --tag=world
    php artisan migrate
    php artisan db:seed --class=WorldSeeder  # (~15 min runtime)
    
    • Verify the world database tables (countries, states, cities, etc.) exist in your migrations folder.
  2. First Query (Facade)

    use eka\World\World;
    
    $countries = World::countries()->data;
    
    • Check $countries for an array of country objects with id, name, and code.
  3. First Query (API Route)

    • Visit /api/countries (or your configured route) to see a JSON response of all countries.
    • Test filtering: /api/countries?search=usa or /api/states?filters[country_code]=US.

Where to Look First

  • Facade API: eka\World\World class (documented in src/World.php).
  • API Routes: Published in routes/web.php (check config/world.php for customization).
  • Database Schema: database/migrations/ for table structures (e.g., states has country_code as a foreign key).
  • Seeder: database/seeders/WorldSeeder.php (for debugging seeding issues).

First Use Case: Country Dropdown

// In a Blade template or controller
$countries = World::countries()->data;
return view('locations.select-country', compact('countries'));
<select name="country">
    @foreach($countries as $country)
        <option value="{{ $country->code }}">{{ $country->name }}</option>
    @endforeach
</select>

Implementation Patterns

Core Workflows

1. Data Retrieval

  • Facade Methods:

    // Get all countries with eager-loaded states
    $countries = World::countries()->with('states')->data;
    
    // Get a single country by code
    $country = World::country('US')->data;
    
    // Get states for a country (with cities)
    $states = World::states(['country_code' => 'US'])->with('cities')->data;
    
    • Chaining: Use ->with() to eager-load relationships (e.g., states, cities, timezones).
  • API Endpoints:

    • /api/countries (GET): List all countries.
    • /api/countries/{code} (GET): Single country.
    • /api/states?filters[country_code]=US (GET): Filter states by country.
    • Fields Parameter: Limit response fields (e.g., ?fields=id,name,code).

2. Filtering and Searching

  • Facade:
    // Search countries by name
    $results = World::countries(['search' => 'rom'])->data;
    
    // Filter states by country code and region code
    $states = World::states([
        'country_code' => 'US',
        'region_code' => 'CA'  // e.g., California
    ])->data;
    
  • API:
    /api/cities?filters[country_code]=US&filters[state_code]=CA
    

3. Relationships

  • Eager Loading:
    // Get countries with their states and cities
    $countries = World::countries()->with(['states.cities'])->data;
    
    • Supported relationships:
      • states (for countries)
      • cities (for states)
      • timezones, currencies, languages (for countries).

4. Customizing Responses

  • Selective Fields:

    $countries = World::countries(['fields' => 'id,name,code'])->data;
    
    • API equivalent: /api/countries?fields=id,name,code.
  • Pagination (API only):

    /api/countries?page=2&per_page=10
    

Integration Tips

1. Form Validation

Use the package to validate country/state/city codes:

use eka\World\Rules\ValidCountryCode;

$request->validate([
    'country_code' => ['required', new ValidCountryCode],
    'state_code' => ['required_if:country_code,US', 'string', 'max:5'],
]);

2. Caching Responses

Cache frequent queries (e.g., country lists) in AppServiceProvider:

public function boot()
{
    Cache::remember('world.countries', now()->addHours(1), function () {
        return World::countries()->data;
    });
}

3. Localization

Override country/state names for localization:

// In a language file (e.g., resources/lang/en/countries.php)
return [
    'US' => 'United States of America',
    'GB' => 'United Kingdom',
];
  • Extend the eka\World\World facade to merge these translations.

4. Testing

Mock the facade in tests:

$mockCountries = collect([new Country(['code' => 'US', 'name' => 'USA'])]);
World::shouldReceive('countries')->andReturn((object) ['success' => true, 'data' => $mockCountries]);

5. Extending the Database

Add custom fields to existing tables via migrations:

Schema::table('countries', function (Blueprint $table) {
    $table->string('iso3')->nullable()->after('code');
});
  • Update the seeder (WorldSeeder) to populate new fields.

Gotchas and Tips

Pitfalls

  1. Seeder Runtime:

    • The WorldSeeder takes ~15 minutes to run. Seed in a staging environment first.
    • Fix: Use --force to skip existing data:
      php artisan db:seed --class=WorldSeeder --force
      
  2. State Code Length:

    • Older versions had a state_code length limit of 3 characters. v1.1.28+ supports up to 5.
    • Fix: If migrating, update your database schema:
      Schema::table('states', function (Blueprint $table) {
          $table->string('code')->change();
      });
      
  3. API Route Conflicts:

    • Published routes (/api/countries, /api/states) may conflict with existing routes.
    • Fix: Customize the prefix in config/world.php:
      'api_prefix' => 'geo',
      
  4. Case Sensitivity:

    • Country/state codes are case-sensitive (e.g., USus).
    • Fix: Normalize inputs:
      $countryCode = strtoupper($request->input('country_code'));
      
  5. Missing Relationships:

    • Not all countries/states have cities or timezones. Check for null:
      $country = World::country('BV')->data; // Bouvet Island (no cities)
      if (!$country->states->isEmpty()) { ... }
      

Debugging

  1. Seeder Errors:

    • Check storage/logs/laravel.log for seeder failures.
    • Tip: Seed incrementally by commenting out chunks in WorldSeeder.php.
  2. API Response Issues:

    • Verify the success flag:
      if (!World::countries()->success) {
          Log::error('World API error:', ['data' => World::countries()->data]);
      }
      
  3. Database Mismatches:

    • Compare database/migrations/ with the package’s default schema (in src/database/migrations/).
    • Fix: Rollback and re-migrate:
      php artisan migrate:rollback
      php artisan migrate
      

Tips

  1. Performance:

    • Indexing: Add indexes to foreign keys for faster queries:
      Schema::table('states', function (Blueprint $table) {
          $table->foreign('country_code')->references('code')->on('countries')->onDelete('cascade');
      });
      
    • Caching: Cache API responses for static data (e.g., country lists).
  2. Extending the Package:

    • Add Custom Fields: Extend the Country, State, or City models (published in app/Models/ after publishing).
    • Example: Add a flag_url to countries:
      // app/Models/Country.php
      protected $appends = ['flag_url'];
      public function getFlagUrlAttribute() {
          return "https://flagcdn.com/w80/{$this->code}.png";
      }
      
  3. Testing Locally:

    • Use the demo API (https://laravel-world.com/api/countries) as a fallback if seeding fails.
  4. Configuration:

    • Customize in
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