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

Country List Laravel Package

umpirsky/country-list

Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require umpirsky/country-list
    

    Add the service provider in config/app.php (Laravel 5.5+ auto-discovers, but explicit registration ensures compatibility):

    'providers' => [
        // ...
        Umpirsky\CountryList\CountryListServiceProvider::class,
    ],
    
  2. First Use Case: Fetching Countries Access the country list via the facade (auto-registered):

    use Umpirsky\CountryList\Facades\CountryList;
    
    $countries = CountryList::getList(); // Returns array of all countries
    $country = CountryList::get('US');   // Get country by ISO code (e.g., 'US')
    
  3. Language Support Specify a language (default: en):

    CountryList::getList('es'); // Spanish names
    CountryList::get('DE', 'fr'); // Germany in French
    
  4. Data Formats Retrieve data in JSON, XML, or CSV:

    $json = CountryList::getList('en', 'json');
    $xml  = CountryList::getList('de', 'xml');
    

Implementation Patterns

Common Workflows

  1. User Registration/Profile Forms Dynamically populate country dropdowns with localized names:

    $countries = CountryList::getList('pt'); // Portuguese names
    return view('register', compact('countries'));
    
  2. API Responses Return localized country data in API responses:

    return response()->json([
        'country' => CountryList::get($request->country_code, $request->lang)
    ]);
    
  3. Validation Rules Create reusable validation rules for ISO codes:

    use Umpirsky\CountryList\Rules\ValidCountryCode;
    
    $request->validate([
        'country' => ['required', new ValidCountryCode],
    ]);
    
  4. Caching Cache the country list for performance (e.g., in AppServiceProvider):

    public function boot()
    {
        Cache::remember('countries', now()->addDays(30), function () {
            return CountryList::getList();
        });
    }
    

Integration Tips

  • Blade Directives: Create a custom Blade directive for easy country name rendering:

    Blade::directive('country', function ($code) {
        return "<?php echo \\Umpirsky\\CountryList\Facades\\CountryList::get($code); ?>";
    });
    

    Usage:

    <select>
        @foreach(CountryList::getList() as $country)
            <option value="{{ $country['iso'] }}">{{ $country['name'] }}</option>
        @endforeach
    </select>
    
  • Localization: Combine with Laravel’s localization system for seamless multilingual support:

    $lang = app()->getLocale();
    $countries = CountryList::getList($lang);
    
  • Database Seeding: Seed a countries table with ISO codes and localized names:

    CountryList::getList()->each(function ($country) {
        Country::updateOrCreate(['iso' => $country['iso']], [
            'name' => $country['name'],
            'native' => $country['native'],
        ]);
    });
    

Gotchas and Tips

Pitfalls

  1. Language Fallbacks

    • If a language isn’t supported, the package defaults to English. Always handle fallbacks:
      $lang = $request->has('lang') ? $request->lang : 'en';
      $country = CountryList::get('FR', $lang ?? 'en');
      
  2. Case Sensitivity

    • ISO codes are case-insensitive, but the package expects uppercase (e.g., 'US' not 'us'). Normalize inputs:
      $iso = strtoupper($request->country_code);
      
  3. Performance with Large Lists

    • Avoid fetching the full list in loops or high-traffic endpoints. Cache aggressively or fetch only needed data:
      $country = CountryList::get('CA'); // Single lookup (faster than full list)
      
  4. Deprecated Codes

    • Some ISO codes (e.g., 'CS' for Yugoslavia) are obsolete. Validate against the latest ISO standards if strict compliance is needed.

Debugging

  • Missing Data: Use CountryList::getList('en', 'json') to inspect raw data for debugging.
  • Locale Issues: Verify the language code matches the package’s supported languages (e.g., 'zh-CN' for Chinese may not work; use 'zh' instead).

Extension Points

  1. Custom Data Formats Extend the package to support additional formats (e.g., YAML):

    // In a service provider
    CountryList::extend('yaml', function () {
        return \Spatie\ArrayToXml\ArrayToXml::convert(
            CountryList::getList(),
            'countries'
        );
    });
    
  2. Database Integration Create a model to wrap country data:

    class Country extends Model
    {
        protected static function boot()
        {
            parent::boot();
            static::bootLoadCountries();
        }
    
        public static function bootLoadCountries()
        {
            static::withoutEvents(function () {
                CountryList::getList()->each(function ($country) {
                    static::updateOrCreate(
                        ['iso' => $country['iso']],
                        $country
                    );
                });
            });
        }
    }
    
  3. Testing Mock the facade for unit tests:

    $this->mock(Umpirsky\CountryList\Facades\CountryList::class)
         ->shouldReceive('get')
         ->with('US')
         ->andReturn(['name' => 'United States']);
    
  4. Configuration Override default behavior via config (config/country-list.php):

    'default_language' => 'es',
    'cache_enabled' => true,
    'cache_ttl' => 86400, // 1 day
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware