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

Php Isocodes Db Only Laravel Package

sokil/php-isocodes-db-only

Database-only package for sokil/php-isocodes: ISO 3166-1 countries, 3166-2 subdivisions, 639-3 languages, 4217 currencies, and 15924 scripts. No i18n/localized names. Updated monthly (2nd day).

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package:

    composer require sokil/php-isocodes sokil/php-isocodes-db-only
    
    • This installs the core library and the database-only package (no translations).
  2. First Use Case: Fetch a Country

    use Sokil\IsoCodes\IsoCodes;
    
    // Get country by ISO alpha-2 code
    $country = IsoCodes::getCountry('US');
    echo $country->name; // "United States"
    echo $country->alpha2; // "US"
    echo $country->alpha3; // "USA"
    
    // Get subdivisions (e.g., US states)
    $subdivisions = IsoCodes::getSubdivisions('US');
    foreach ($subdivisions as $subdivision) {
        echo $subdivision->name; // "California", "Texas", etc.
    }
    
  3. Where to Look First:

    • Facade: IsoCodes is the primary entry point for all ISO code lookups.
    • Models: Country, Subdivision, Language, Currency, and Script classes provide structured data access.
    • Documentation: Check the core library's README for advanced usage (e.g., caching, custom data sources).
  4. Database Integration (Optional): If you need to persist ISO data in your Laravel database:

    • Inspect the SQL dump in the package’s resources/sql/ (if available) or use the library’s built-in data.
    • Create a migration to import the data into your schema:
      php artisan make:migration import_iso_codes --table=countries
      

Implementation Patterns

Usage Patterns

  1. Basic Lookups:

    // Countries
    $country = IsoCodes::getCountry('GB'); // United Kingdom
    $countryName = $country->name;
    
    // Subdivisions (e.g., UK regions)
    $subdivisions = IsoCodes::getSubdivisions('GB');
    $firstSubdivision = $subdivisions[0]->name; // "England"
    
    // Languages
    $language = IsoCodes::getLanguage('eng'); // English
    $languageName = $language->name;
    
    // Currencies
    $currency = IsoCodes::getCurrency('USD'); // US Dollar
    $currencySymbol = $currency->symbol; // "$"
    
  2. Validation in Laravel Forms:

    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($request->all(), [
        'country_code' => [
            'required',
            function ($attribute, $value, $fail) {
                if (!IsoCodes::hasCountry($value)) {
                    $fail('The '.$attribute.' must be a valid ISO country code.');
                }
            },
        ],
        'language_code' => [
            'required',
            function ($attribute, $value, $fail) {
                if (!IsoCodes::hasLanguage($value)) {
                    $fail('The '.$attribute.' must be a valid ISO language code.');
                }
            },
        ],
    ]);
    
  3. Dynamic Dropdowns in Blade:

    <select name="country">
        @foreach(IsoCodes::getCountries() as $country)
            <option value="{{ $country->alpha2 }}">
                {{ $country->name }}
            </option>
        @endforeach
    </select>
    
  4. Caching for Performance:

    use Illuminate\Support\Facades\Cache;
    
    $countries = Cache::remember('iso.countries.all', now()->addDays(30), function () {
        return IsoCodes::getCountries();
    });
    
  5. Integration with Eloquent: Create a trait or service to extend Eloquent models:

    use Sokil\IsoCodes\IsoCodes;
    
    trait HasIsoCountry
    {
        public function getCountryAttribute($value)
        {
            return IsoCodes::getCountry($value);
        }
    }
    
    // Usage in a model:
    class User extends Model
    {
        use HasIsoCountry;
    }
    
    // Query:
    $user = User::whereHas('country', function ($query) {
        $query->where('alpha2', 'US');
    })->first();
    

Workflows

  1. User Registration with Country Selection:

    • Use the package to validate and display country/subdivision dropdowns.
    • Store only the ISO code in the database (e.g., country_code column) and fetch the full object when needed.
  2. Multi-Currency Support:

    • Validate currency codes during checkout:
      $currency = IsoCodes::getCurrency($request->currency);
      if (!$currency) {
          abort(422, 'Invalid currency code.');
      }
      
    • Format amounts using the currency’s symbol or name.
  3. Localization and Routing:

    • Use ISO language codes to route users to language-specific content:
      $language = IsoCodes::getLanguage($request->lang);
      return redirect()->route('home', ['lang' => $language->alpha3]);
      
  4. Data Migration:

    • Seed your database with ISO data during deployment:
      use Sokil\IsoCodes\IsoCodes;
      use Illuminate\Database\Seeder;
      
      class ImportIsoCodes extends Seeder
      {
          public function run()
          {
              DB::table('countries')->insert(
                  array_map(function ($country) {
                      return [
                          'iso_alpha2' => $country->alpha2,
                          'iso_alpha3' => $country->alpha3,
                          'name' => $country->name,
                          // ... other fields
                      ];
                  }, IsoCodes::getCountries())
              );
          }
      }
      

Integration Tips

  1. Laravel Service Providers: Bind the IsoCodes facade for easier dependency injection:

    // In AppServiceProvider
    public function register()
    {
        $this->app->bind('isoCodes', function () {
            return new \Sokil\IsoCodes\IsoCodes();
        });
    }
    
  2. API Responses: Return ISO data in API responses for consistency:

    return response()->json([
        'country' => [
            'code' => $country->alpha2,
            'name' => $country->name,
            'currency' => $country->currency->alpha3,
        ],
    ]);
    
  3. Testing: Mock the IsoCodes facade in tests to avoid hitting the database:

    $this->mock(\Sokil\IsoCodes\IsoCodes::class, function ($mock) {
        $mock->shouldReceive('getCountry')
             ->with('US')
             ->andReturn((object) ['name' => 'United States', 'alpha2' => 'US']);
    });
    
  4. Custom Data Sources: If you need to extend the ISO data, subclass the core library:

    use Sokil\IsoCodes\IsoCodes as BaseIsoCodes;
    
    class CustomIsoCodes extends BaseIsoCodes
    {
        public function getCustomCountries()
        {
            $countries = parent::getCountries();
            // Add custom logic or data
            return $countries;
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity:

    • ISO codes (e.g., US, GB) are case-sensitive in some implementations. Always use uppercase:
      $country = IsoCodes::getCountry('us'); // May return null
      $country = IsoCodes::getCountry('US'); // Correct
      
  2. Missing Subdivisions:

    • Not all countries have subdivisions (e.g., ISO 3166-2 may not exist for some nations). Handle missing data gracefully:
      $subdivisions = IsoCodes::getSubdivisions('US') ?: collect();
      
  3. Database Schema Mismatches:

    • If importing the SQL dump directly, ensure your Laravel schema matches the package’s structure. For example:
      • iso_alpha2 should be CHAR(2) or VARCHAR(2) (not longer).
      • name fields may contain non-ASCII characters (use UTF-8 collation).
  4. Monthly Updates:

    • The database updates monthly (2nd of each month). If you rely on specific data (e.g., new countries), test updates thoroughly:
      composer update sokil/php-isocodes-db-only
      php artisan migrate:fresh --seed  # If using migrations/seeds
      
  5. No Translations:

    • This package does not include translations. If you need localized names (e.g., "États-Unis" for France), use sokil/php-isocodes-db-i18n or implement a translation layer.
  6. Performance with Large Datasets:

    • Fetching all subdivisions for a country with many regions (e.g., India) can be slow. Cache results:
      Cache::remember("subdivisions.{$countryCode}", now()->addHours(1), function () use ($countryCode)
      
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky