Weave 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

monarobase/country-list

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require monarobase/country-list
    

    No additional configuration is required—just autoload the package.

  2. First Use Case: Fetching Countries in English

    use MonaroBase\CountryList\Facades\CountryList;
    
    $countries = CountryList::getCountries('en');
    // Returns an array of all countries with ISO codes and names in English
    
  3. Where to Look First

    • Facade: CountryList provides a clean interface for common operations.
    • Helper Methods: Check CountryList::getCountries(), CountryList::getCountry(), and CountryList::getCountryByCode().
    • Data Formats: Supports JSON, XML, and array formats via CountryList::getCountries('en', 'json').

Implementation Patterns

Common Workflows

  1. Fetching Countries in Multiple Languages

    $languages = ['en', 'es', 'fr'];
    $countries = collect($languages)->map(fn($lang) => CountryList::getCountries($lang));
    
  2. Integrating with Forms/Validation

    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($request->all(), [
        'country_code' => 'required|country_code',
    ]);
    // Requires custom rule: `CountryCodeRule` (see below)
    
  3. Custom Rule for Country Code Validation

    use MonaroBase\CountryList\Rules\CountryCode;
    
    $validator = Validator::make($request->all(), [
        'country_code' => ['required', new CountryCode],
    ]);
    
  4. Caching for Performance

    $cachedCountries = Cache::remember('countries_en', now()->addHours(1), function () {
        return CountryList::getCountries('en');
    });
    
  5. Blade Directives for Views

    // In a service provider:
    Blade::directive('country', function ($code) {
        return "<?php echo \\MonaroBase\\CountryList\\Facades\\CountryList::getCountryName('{$code}', app()->getLocale()); ?>";
    });
    
    // In Blade:
    @country('US') // Outputs "United States" (or localized equivalent)
    
  6. Exporting Data to CSV/Excel

    use Maatwebsite\Excel\Facades\Excel;
    
    Excel::download(new CountriesExport('en'), 'countries.csv');
    

    (Requires maatwebsite/excel and a custom CountriesExport class.)


Gotchas and Tips

Pitfalls

  1. Locale Fallback

    • If a language isn’t supported, the package defaults to en. Always validate available languages with:
      CountryList::getAvailableLanguages(); // Returns array of supported locales
      
  2. Case Sensitivity in ISO Codes

    • ISO codes (e.g., US, us) are case-insensitive in the package, but always use uppercase for consistency:
      CountryList::getCountry('US'); // Correct
      CountryList::getCountry('us'); // Works but discouraged
      
  3. Memory Usage for Large Exports

    • Fetching all countries in JSON/XML can be memory-intensive. Use chunking or streaming for large datasets:
      $countries = CountryList::getCountries('en', 'json', ['chunk' => 1000]);
      
  4. Deprecated Methods

    • Avoid CountryList::all() (deprecated in favor of CountryList::getCountries()).

Debugging Tips

  1. Verify Data Integrity

    • Check for missing translations or invalid ISO codes:
      $invalidCodes = CountryList::getCountries('en')->filter(fn($country) => empty($country['name']));
      
  2. Logging Unsupported Languages

    • Wrap calls in a try-catch to log unsupported locales:
      try {
          $countries = CountryList::getCountries('xx'); // Hypothetical unsupported lang
      } catch (\InvalidArgumentException $e) {
          Log::warning("Unsupported language: xx", ['exception' => $e]);
      }
      
  3. Testing Edge Cases

    • Test with:
      • Non-existent ISO codes (e.g., CountryList::getCountry('ZZ')).
      • Empty language strings (e.g., CountryList::getCountries('')).

Extension Points

  1. Custom Data Formats

    • Extend the package by creating a custom formatter:
      CountryList::extend('custom', function ($countries, $lang) {
          return collect($countries)->map(fn($c) => [
              'code' => $c['code'],
              'name' => strtoupper($c['name']),
          ]);
      });
      // Usage: CountryList::getCountries('en', 'custom')
      
  2. Adding New Languages

    • The package doesn’t support dynamic language addition, but you can fork the package and extend the languages array in CountryListServiceProvider.
  3. Integration with Eloquent

    • Add a country_code trait to models:
      use MonaroBase\CountryList\Traits\HasCountryCode;
      
      class User extends Model {
          use HasCountryCode;
      }
      // Automatically validates and localizes country codes
      
  4. API Response Wrapping

    • Wrap responses for APIs:
      return response()->json([
          'data' => CountryList::getCountries('en'),
          'meta' => ['count' => count(CountryList::getCountries('en'))],
      ]);
      
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.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings