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

sokil/php-isocodes

PHP library for ISO code datasets with localized names: countries (ISO 3166-1/2/3), currencies (ISO 4217), languages (ISO 639-3) and scripts (ISO 15924). Supports Gettext or Symfony Translation drivers, with locale configuration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package (choose based on needs):

    composer require sokil/php-isocodes-db-i18n  # With database + translations (recommended)
    # OR
    composer require sokil/php-isocodes-db-only  # With database only (no translations)
    
  2. Basic usage (for countries):

    use Sokil\IsoCodes\IsoCodesFactory;
    
    $isoCodes = new IsoCodesFactory();
    $country = $isoCodes->getCountries()->getByAlpha2('US');
    echo $country->getName(); // "United States of America"
    
  3. Localization setup (if using translations):

    // For Gettext (default)
    putenv('LANGUAGE=en_US.UTF-8');
    setlocale(LC_ALL, 'en_US.UTF-8');
    
    // OR for Symfony Translation Driver
    $driver = new SymfonyTranslationDriver();
    $driver->setLocale('fr_FR');
    $isoCodes = new IsoCodesFactory(null, $driver);
    

First Use Case

Display localized country names in a Laravel view:

// In a controller
$countries = collect($isoCodes->getCountries())
    ->mapWithKeys(fn($country) => [$country->getAlpha2() => $country->getLocalName()]);

return view('countries.index', ['countries' => $countries]);

Implementation Patterns

Common Workflows

  1. Country Selection Dropdown

    $countries = $isoCodes->getCountries()->getAll();
    $options = collect($countries)->pluck('name', 'alpha2');
    
  2. Subdivision Lookup (e.g., US States)

    $subdivisions = $isoCodes->getSubdivisions()->getByCountryAlpha2('US');
    $states = $subdivisions->filter(fn($s) => $s->getType() === 'State');
    
  3. Currency Conversion Helper

    $currency = $isoCodes->getCurrencies()->getByLetterCode('EUR');
    $formatted = $currency->getLocalName() . ' ' . number_format($amount, 2);
    
  4. Language Detection Middleware

    public function handle($request, Closure $next) {
        $lang = $request->header('Accept-Language') ?? 'en';
        $driver = new SymfonyTranslationDriver();
        $driver->setLocale($lang);
        app()->singleton(IsoCodesFactory::class, fn() => new IsoCodesFactory(null, $driver));
        return $next($request);
    }
    

Integration Tips

  • Service Provider Binding:

    public function register() {
        $this->app->singleton(IsoCodesFactory::class, function() {
            $driver = new SymfonyTranslationDriver();
            $driver->setLocale(config('app.locale'));
            return new IsoCodesFactory(null, $driver);
        });
    }
    
  • Eloquent Model Traits:

    trait HasCountryCodes {
        public function getCountryNameAttribute() {
            return $this->country_code
                ? app(IsoCodesFactory::class)->getCountries()->getByAlpha2($this->country_code)?->getLocalName()
                : null;
        }
    }
    
  • API Response Formatting:

    return response()->json([
        'country' => [
            'code' => $country->getAlpha2(),
            'name' => $country->getName(),
            'local_name' => $country->getLocalName(),
            'flag' => $country->getFlag(),
        ]
    ]);
    
  • Caching Strategy:

    $cacheKey = 'iso_countries_' . config('app.locale');
    return Cache::remember($cacheKey, now()->addHours(1), function() {
        return collect($isoCodes->getCountries());
    });
    

Gotchas and Tips

Pitfalls

  1. Locale Configuration:

    • Forgetting to set setlocale() before using translations will return empty strings.
    • System locales must be installed (e.g., locale-gen uk_UA.utf8 on Ubuntu).
  2. Memory Usage:

    • Loading all subdivisions/languages at once can consume significant RAM. Use lazy loading:
      $isoCodes->getSubdivisions()->setMemoryOptimization(true);
      
  3. Flag Handling:

    • Flags are returned as base64-encoded strings. Decode before displaying:
      base64_decode($country->getFlag());
      
  4. Translation Driver Conflicts:

    • Mixing Gettext and Symfony drivers may cause unexpected behavior. Stick to one per application.
  5. Database Updates:

    • If using sokil/php-isocodes (without bundled DB), remember to run:
      ./bin/update_iso_codes_db.sh all /path/to/storage
      

Debugging Tips

  • Verify Locale:

    echo setlocale(LC_ALL, 0); // Check current locale
    
  • Check Available Locales:

    locale -a
    
  • Memory Profiling:

    $memoryBefore = memory_get_usage();
    $countries = $isoCodes->getCountries();
    $memoryAfter = memory_get_usage();
    echo "Memory used: " . ($memoryAfter - $memoryBefore) / 1024 / 1024 . "MB";
    
  • Common Errors:

    • Undefined locale → Install missing locale (e.g., sudo apt-get install locales-all).
    • No such file or directory → Verify database path in IsoCodesFactory.

Extension Points

  1. Custom Translation Driver:

    class LaravelTranslationDriver implements TranslationDriverInterface {
        public function translate($message, $locale) {
            return trans("iso_codes.$message", [], null, $locale);
        }
    }
    
  2. Database Filtering:

    $activeCountries = collect($isoCodes->getCountries())
        ->reject(fn($c) => $c->getWithdrawalDate() !== null);
    
  3. Hybrid Caching:

    $cache = Cache::rememberForever('iso_countries', function() {
        return collect($isoCodes->getCountries())
            ->mapToGroups(fn($country) => [$country->getContinent() => $country]);
    });
    
  4. Event Listeners for Updates:

    // In a service provider
    $this->app->booted(function() {
        if (config('iso_codes.auto_update')) {
            Artisan::call('iso:update');
        }
    });
    

Laravel-Specific Tips

  • Publish Config:

    php artisan vendor:publish --provider="Sokil\IsoCodes\IsoCodesServiceProvider"
    
  • Artisan Command for Updates:

    // app/Console/Commands/UpdateIsoCodes.php
    public function handle() {
        $this->call('vendor:publish', ['--provider' => 'Sokil\IsoCodes\IsoCodesServiceProvider']);
        $this->info('ISO codes updated!');
    }
    
  • Blade Directives:

    // In a service provider
    Blade::directive('isoCountry', function($code) {
        return "<?php echo app('Sokil\\IsoCodes\\IsoCodesFactory')->getCountries()->getByAlpha2($code)?->getLocalName(); ?>";
    });
    

    Usage in Blade:

    @isoCountry('US')  <!-- Outputs localized country name -->
    
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
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
spatie/mailcoach-vapor