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

tocaan/world

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require tocaan/world
    php artisan vendor:publish --tag=world
    php artisan migrate
    php artisan db:seed --class=WorldSeeder
    
    • Verify the package is installed by checking the world config file in config/world.php and the published migrations/seeder in database/migrations/.
  2. First Use Case:

    • Facade Usage: Fetch all countries via the facade:
      use Tocaan\World\Facades\World;
      
      $countries = World::countries();
      
    • API Route: Access the API endpoint directly:
      GET /api/countries
      

Where to Look First

  • Config File: config/world.php (customize table names, optional fields, or restrict countries via allowed_countries/disallowed_countries).
  • Facade: Tocaan\World\Facades\World (primary interface for data retrieval).
  • API Routes: /api/countries, /api/states/{country_code}, etc. (documented in the package).
  • Seeder: database/seeders/WorldSeeder.php (understand the data structure before querying).

Implementation Patterns

Core Workflows

  1. Data Retrieval via Facade:

    • Fetch hierarchical data (e.g., states/cities under a country):
      $states = World::states('US'); // States for the USA
      $cities = World::cities('US', 'CA'); // Cities in California
      
    • Filter results with the search argument (v1.1.12+):
      $countries = World::countries()->search('France');
      
  2. API Integration:

    • Use the built-in API routes for frontend consumption:
      // Fetch countries via JavaScript
      fetch('/api/countries')
        .then(response => response.json())
        .then(data => console.log(data));
      
    • Customize API responses by extending the WorldController (published with vendor:publish).
  3. Database-Driven Customization:

    • Restrict Countries: Update config/world.php:
      'allowed_countries' => ['US', 'CA', 'GB'], // Only seed these countries
      'disallowed_countries' => ['RU', 'CN'],   // Exclude these
      
    • Optional Fields: Enable/disable fields like subregion or currency_code in the config.
  4. Eager Loading:

    • Optimize queries by loading related data (e.g., countries with their currencies/timezones):
      $countries = World::countries()->with(['currencies', 'timezones'])->get();
      
    • Note: Requires defining relationships in the Country, State, etc., models (extend the published models if needed).

Integration Tips

  • Form Validation: Use the package data for dynamic validation (e.g., check if a state exists for a country):
    use Tocaan\World\Facades\World;
    
    $validator = Validator::make($request->all(), [
        'state' => ['required', function ($attribute, $value, $fail) use ($request) {
            $countryCode = $request->country;
            if (!World::states($countryCode)->contains('name', $value)) {
                $fail('The selected state is invalid for the chosen country.');
            }
        }],
    ]);
    
  • Localization: Pair with Laravel’s localization features to display country/state names in multiple languages.
  • Caching: Cache frequent queries (e.g., all countries) to reduce database load:
    $countries = Cache::remember('world.countries', now()->addHours(1), function () {
        return World::countries()->get();
    });
    

Gotchas and Tips

Pitfalls

  1. Migration/Seeder Conflicts:

    • If upgrading from <1.1.10, run php artisan vendor:publish --tag=world --force to avoid route/config conflicts.
    • The sub_region field was renamed to subregion in v1.1.12. If you’ve customized migrations, update them or refresh the database.
  2. Case Sensitivity:

    • Country/state/city names in the database are case-sensitive when using the search argument. Normalize inputs:
      $results = World::countries()->search(strtolower($searchTerm))->get();
      
  3. API Route Overrides:

    • The package publishes a WorldController. If you override it, ensure you replicate all methods (e.g., countries(), states(), etc.) to avoid broken endpoints.
  4. Optional Fields:

    • Fields like currency_code or timezone are optional by default. If your app requires them, enable them in config/world.php and re-run the seeder:
      'optional_fields' => [
          'currencies' => true,
          'timezones' => true,
      ],
      

Debugging

  • Missing Data: Verify the seeder ran successfully (php artisan db:seed --class=WorldSeeder). Check the countries, states, and cities tables directly if queries return empty.
  • API 404s: Ensure you’ve published the config and migrations. Check routes/web.php for the package’s API routes:
    Route::prefix('api')->group(function () {
        Route::get('/countries', [\Tocaan\World\Http\Controllers\WorldController::class, 'countries']);
        // ... other routes
    });
    
  • Performance: Large datasets (e.g., all cities globally) may time out. Use pagination or caching:
    $cities = World::cities()->paginate(50);
    

Extension Points

  1. Custom Models:

    • Extend the published models (Country, State, City, etc.) to add custom logic or relationships:
      // app/Models/CustomCountry.php
      class CustomCountry extends \Tocaan\World\Models\Country {
          public function regions() {
              return $this->hasMany(CustomRegion::class);
          }
      }
      
    • Update the facade or API controller to use your custom models.
  2. Additional Data Sources:

    • Add custom tables for extended attributes (e.g., country_phone_codes) and join them in queries:
      $countries = World::countries()
          ->join('country_phone_codes', 'countries.code', '=', 'country_phone_codes.country_code')
          ->select('countries.*', 'country_phone_codes.code as phone_code')
          ->get();
      
  3. Dynamic Seeding:

    • Override the WorldSeeder to filter or transform data before seeding:
      // database/seeders/CustomWorldSeeder.php
      class CustomWorldSeeder extends \Tocaan\World\Database\Seeders\WorldSeeder {
          protected function getCountries() {
              return parent::getCountries()->where('region', 'Europe');
          }
      }
      
    • Run your custom seeder instead:
      php artisan db:seed --class=CustomWorldSeeder
      
  4. Testing:

    • Use the facade directly in tests to avoid database dependencies:
      public function test_country_retrieval() {
          $countries = World::countries();
          $this->assertCount(195, $countries); // Example assertion
      }
      
    • For API tests, mock the WorldController or use the published routes.
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
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