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

sokil/php-isocodes-db-i18n

Lightweight PHP library bundling ISO Codes database with i18n support. Look up ISO country, language, script and currency codes and get localized names via simple API. Useful for forms, dropdowns, validation and locale-aware apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require sokil/php-isocodes-db-i18n
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Sokil\IsoCodes\IsoCodesServiceProvider::class,
    ],
    
  2. Publish Config & Database

    php artisan vendor:publish --provider="Sokil\IsoCodes\IsoCodesServiceProvider" --tag="config"
    php artisan vendor:publish --provider="Sokil\IsoCodes\IsoCodesServiceProvider" --tag="migrations"
    

    Run migrations:

    php artisan migrate
    
  3. First Query

    use Sokil\IsoCodes\Facades\IsoCodes;
    
    // Get country by ISO code (e.g., 'US')
    $country = IsoCodes::country('US');
    echo $country->name; // "United States"
    
    // Get country by name (English)
    $country = IsoCodes::countryByName('United States');
    
  4. Localization Ensure your app’s locale is set (e.g., config/app.php):

    'locale' => 'en', // or 'fr', 'es', etc.
    

Implementation Patterns

Core Workflows

  1. Fetching Entities

    // Countries
    $countries = IsoCodes::countries()->limit(10)->get();
    $country = IsoCodes::country('GB');
    
    // Subdivisions (e.g., US states)
    $states = IsoCodes::subdivisions('US')->get();
    $state = IsoCodes::subdivision('US', 'CA'); // California
    
    // Languages
    $languages = IsoCodes::languages()->get();
    $language = IsoCodes::language('en');
    
  2. Localized Output Dynamically switch locales in runtime:

    app()->setLocale('fr');
    $country = IsoCodes::country('FR');
    echo $country->name; // "France" (localized)
    
  3. Integration with Eloquent Attach ISO codes to models (e.g., User):

    use Sokil\IsoCodes\Traits\HasIsoCodes;
    
    class User extends Model
    {
        use HasIsoCodes;
    }
    
    // Usage:
    $user = new User();
    $user->setCountry('US'); // Stores 'country_code' in DB
    $user->country->name; // Localized name
    
  4. Validation Validate ISO codes in Form Requests:

    use Sokil\IsoCodes\Rules\ValidCountryCode;
    
    public function rules()
    {
        return [
            'country_code' => ['required', new ValidCountryCode],
        ];
    }
    
  5. Caching Enable caching for performance (add to config/isocodes.php):

    'cache' => [
        'enabled' => true,
        'driver' => 'file', // or 'redis', 'database'
    ],
    

    Clear cache when data updates:

    php artisan cache:clear
    

Advanced Patterns

  1. Custom Queries Extend the query builder for custom filters:

    $countries = IsoCodes::countries()
        ->where('official_name', 'like', '%United%')
        ->where('region', 'EU')
        ->get();
    
  2. API Integration Fetch remote updates (if supported in future versions):

    // Hypothetical: Sync with ISO online database
    IsoCodes::syncWithIsoDatabase();
    
  3. Localization Fallbacks Configure fallback locales in config/isocodes.php:

    'locales' => [
        'fallback' => 'en',
        'supported' => ['en', 'fr', 'es'],
    ],
    
  4. Testing Mock ISO codes in tests:

    $this->partialMock(IsoCodes::class, function ($mock) {
        $mock->shouldReceive('country')
             ->with('US')
             ->andReturn((object) ['name' => 'Mock USA']);
    });
    

Gotchas and Tips

Common Pitfalls

  1. Locale Mismatches

    • Issue: Localized names return unexpected values if the app’s locale isn’t set or supported.
    • Fix: Explicitly set the locale or use fallbacks:
      app()->setLocale('en'); // Fallback to English
      
  2. Database Sync Conflicts

    • Issue: Manual DB updates may conflict with package migrations.
    • Fix: Disable migrations if using custom tables:
      'migrations' => [
          'run' => false, // Set to false in config/isocodes.php
      ],
      
  3. Caching Stale Data

    • Issue: Cached data isn’t refreshed after manual updates.
    • Fix: Clear cache manually or implement a cache:forget strategy:
      Cache::forget('isocodes_countries');
      
  4. Case Sensitivity

    • Issue: ISO codes are case-sensitive (e.g., 'us' vs 'US').
    • Fix: Normalize input:
      $country = IsoCodes::country(strtoupper($userInput));
      
  5. Missing Subdivisions

    • Issue: Some countries lack subdivision data (e.g., 'TT' for Trinidad and Tobago).
    • Fix: Handle exceptions gracefully:
      try {
          $subdivision = IsoCodes::subdivision('TT', '1');
      } catch (\Sokil\IsoCodes\Exceptions\NotFoundException $e) {
          // Fallback logic
      }
      

Debugging Tips

  1. Log Queries Enable query logging in config/isocodes.php:

    'debug' => [
        'log_queries' => true,
    ],
    

    Check storage/logs/laravel.log for raw SQL.

  2. Check Data Integrity Verify DB records with:

    php artisan tinker
    >> Sokil\IsoCodes\Models\Country::count(); // Should match expected records
    
  3. Validate Config Ensure config/isocodes.php paths are correct:

    'database' => [
        'connection' => 'mysql', // Must match your .env
    ],
    

Extension Points

  1. Custom Data Sources Override the default data source by binding a custom repository:

    $this->app->bind(\Sokil\IsoCodes\Contracts\CountryRepository::class, function () {
        return new CustomCountryRepository();
    });
    
  2. Add New Entity Types Extend the package’s Entity class to support custom ISO entities (e.g., currencies):

    class Currency extends \Sokil\IsoCodes\Models\Entity
    {
        protected $table = 'isocodes_currencies';
    }
    
  3. Localization Hooks Add custom translation logic via service provider:

    public function boot()
    {
        IsoCodes::extend('country', function ($code) {
            // Custom logic for country 'XX'
            if ($code === 'XX') {
                return (object) ['name' => __('custom.xx_name')];
            }
        });
    }
    
  4. Event Listeners Listen for ISO code updates (e.g., after migration):

    event(new \Sokil\IsoCodes\Events\DataSynced());
    
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