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 Iso Countries Laravel Package

io238/laravel-iso-countries

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require io238/laravel-iso-countries
    

    Run migrations and seeders:

    php artisan migrate --seed
    
  2. First Use Case Fetch a country by ISO code (e.g., "US"):

    use Io238\LaravelIsoCountries\Models\Country;
    
    $usa = Country::where('iso_alpha2', 'US')->first();
    echo $usa->name; // "United States"
    
  3. Key Models

    • Country (ISO 3166-1 alpha-2)
    • Language (ISO 639-1)
    • Currency (ISO 4217)
    • CountryLanguage (pivot table for country-language relationships)
  4. Multi-Language Support Access localized names via localized():

    $usa->localized('name', 'es'); // "Estados Unidos"
    

Implementation Patterns

Core Workflows

  1. Country Lookups

    • Fetch by ISO code (alpha-2/alpha-3/numeric):
      Country::findByIsoAlpha2('US');
      Country::findByIsoAlpha3('USA');
      Country::findByIsoNumeric('840');
      
    • Search by name (supports locales):
      Country::whereLocalized('name', 'like', '%France%')->get();
      
  2. Relationships

    • Country → Languages/Currencies:
      $canada = Country::find('CA');
      $canada->languages; // Collection of Language models
      $canada->currencies; // Collection of Currency models
      
    • Language → Countries:
      $english = Language::where('iso_alpha2', 'en')->first();
      $english->countries; // Countries where English is official
      
  3. Data Augmentation Use traits in your models to auto-attach ISO data:

    use Io238\LaravelIsoCountries\Traits\HasCountry;
    use Io238\LaravelIsoCountries\Traits\HasLanguage;
    
    class User extends Model {
        use HasCountry, HasLanguage;
    }
    

    Then access via:

    $user->country->name; // User's country name
    
  4. Form Validation Validate ISO codes in Laravel:

    use Io238\LaravelIsoCountries\Rules\ValidIsoAlpha2;
    
    $request->validate([
        'country_code' => ['required', new ValidIsoAlpha2],
    ]);
    
  5. Localization Dynamically fetch translations for the current locale:

    $country = Country::find('JP');
    $country->name; // Auto-resolves to current app locale
    

Integration Tips

  • API Responses: Serialize ISO data in JSON:
    return Country::find('DE')->append('localized_name')->toArray();
    
  • Admin Panels: Use the package’s data for dropdowns (e.g., in Nova/Telescope):
    Country::pluck('name', 'iso_alpha2'); // ['US' => 'United States', ...]
    
  • Geocoding: Combine with lat/lon for maps:
    $country = Country::find('AU');
    ['lat' => $country->lat, 'lng' => $country->lon];
    
  • Seeding: Extend the seeder for custom data:
    use Io238\LaravelIsoCountries\Database\Seeders\IsoCountriesSeeder;
    
    class CustomSeeder extends IsoCountriesSeeder {
        public function run() {
            $this->call([
                // Override or add custom logic
            ]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Locale Mismatches

    • Ensure app.locale in .env matches your expected language (e.g., en, es).
    • Fallback: Explicitly pass a locale to localized():
      $country->localized('name', 'fr'); // Override app locale
      
  2. Database Conflicts

    • If you manually add countries, languages, or currencies to the DB, avoid duplicate ISO codes (e.g., iso_alpha2 must be unique).
    • Fix: Use upsert or disable the package’s seeder if managing data externally.
  3. Performance

    • Eager-load relationships to avoid N+1 queries:
      Country::with(['languages', 'currencies'])->find('GB');
      
    • Tip: Cache frequent queries (e.g., all countries):
      Cache::remember('all_countries', now()->addDays(7), function () {
          return Country::all();
      });
      
  4. Deprecated Methods

    • Check the changelog for breaking changes (e.g., renamed methods like getName()name).

Debugging

  1. Missing Data

    • Verify the iso_countries tables exist and are seeded:
      php artisan db:seed --class=IsoCountriesSeeder
      
    • Check for SQL errors if data is missing (e.g., languages table not populated).
  2. Localization Issues

    • Ensure the localized column exists in the countries/languages/currencies tables.
    • Fix: Re-run migrations or manually add the column:
      php artisan migrate:fresh --seed
      
  3. Relationship Errors

    • If country->languages returns empty, check the country_language pivot table:
      \DB::table('country_language')->count(); // Should return >0
      

Extension Points

  1. Custom Fields Add columns to the countries table (e.g., emoji):

    Schema::table('countries', function (Blueprint $table) {
        $table->string('emoji')->nullable();
    });
    

    Then update the seeder or manually populate.

  2. Additional ISO Standards Extend the package by adding new models (e.g., ISO 3166-2 subdivisions):

    // Example: Add a State model
    class State extends Model {
        public function country() {
            return $this->belongsTo(Country::class);
        }
    }
    
  3. Custom Localization Override the localized() method in your model:

    class Country extends \Io238\LaravelIsoCountries\Models\Country {
        public function localized($attribute, $locale = null) {
            // Custom logic (e.g., fallback to 'en' if locale missing)
        }
    }
    
  4. Testing Use the package’s factories in tests:

    use Io238\LaravelIsoCountries\Database\Factories\CountryFactory;
    
    $country = CountryFactory::new()->create(['iso_alpha2' => 'XK']);
    

Pro Tips

  • Bulk Operations: Use collections for batch updates:
    Country::where('region', 'EU')->update(['custom_flag' => true]);
    
  • API Caching: Cache ISO data in a service layer:
    class CountryService {
        public function getCountryWithCache($isoCode) {
            return Cache::remember("country_{$isoCode}", now()->addHours(1), function () use ($isoCode) {
                return Country::findByIsoAlpha2($isoCode);
            });
        }
    }
    
  • Validation Rules: Reuse the package’s rules in Form Requests:
    use Io238\LaravelIsoCountries\Rules\ValidIsoAlpha3;
    
    $request->validate([
        'country' => ['required', new ValidIsoAlpha3],
    ]);
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
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