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

Countries Laravel Package

aheenam/countries

Laravel wrapper around umpirsky/country-list providing simple country name lookups. Retrieve all countries or a specific country by code, in the current locale or another language via allIn() and get(). Lightweight fallback to antonioribeiro/countries.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require aheenam/countries
    

    Publish the configuration (if needed):

    php artisan vendor:publish --provider="Aheenam\Countries\CountriesServiceProvider"
    
  2. First Use Case: Fetch all countries as an array:

    use Aheenam\Countries\Facades\Countries;
    
    $countries = Countries::all();
    // Returns an array of country data (name, code, etc.)
    
  3. Where to Look First:

    • Facade: Aheenam\Countries\Facades\Countries (primary entry point).
    • Configuration: config/countries.php (if published).
    • Source Data: Check vendor/aheenam/countries/src/Countries/Countries.php for raw data structure.

Implementation Patterns

Common Workflows

  1. Fetching Countries:

    // Get all countries
    $allCountries = Countries::all();
    
    // Get a single country by code
    $country = Countries::get('US');
    
    // Get countries by region (if supported)
    $europeanCountries = Countries::where('region', 'Europe')->get();
    
  2. Integration with Forms/Validation:

    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($request->all(), [
        'country_code' => 'required|country_code', // Uses package's validation rule
    ]);
    
  3. Localization:

    // Override country names (e.g., for translations)
    Countries::setNames([
        'US' => 'United States of America (Custom)',
        'GB' => 'United Kingdom (Custom)',
    ]);
    
  4. Dynamic Data Handling:

    // Filter countries by flag availability
    $countriesWithFlags = collect(Countries::all())
        ->where('flag', '!=', null)
        ->values()
        ->all();
    

Integration Tips

  • Eloquent Relationships:

    // Add to a User model
    public function country()
    {
        return $this->belongsTo(Country::class, 'country_code', 'code');
    }
    

    (Note: Requires a Country model; package doesn’t include one—you’ll need to create it.)

  • Blade Templates:

    @foreach(Countries::all() as $country)
        <option value="{{ $country['code'] }}">
            {{ $country['name'] }}
        </option>
    @endforeach
    
  • API Responses:

    return response()->json([
        'countries' => Countries::all(),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Outdated Data:

    • Last updated in 2017; verify if country names/codes (e.g., "UK" vs. "GB") align with your needs.
    • Workaround: Override data via Countries::setNames() or extend the package.
  2. No Eloquent Model:

    • The package provides raw arrays. You’ll need to create a Country model/seed it manually:
      // Example seeder
      foreach (Countries::all() as $country) {
          Country::updateOrCreate(
              ['code' => $country['code']],
              $country
          );
      }
      
  3. Validation Rule Assumption:

    • The country_code validation rule assumes ISO 3166-1 alpha-2 codes. Test edge cases (e.g., XX for "unknown").
  4. Configuration Overrides:

    • The package may not publish config by default. Check if config/countries.php exists before assuming defaults.

Debugging

  • Data Structure: Inspect the raw output of Countries::all() to confirm fields (e.g., name, code, flag, region). Example output:

    [
        'US' => ['name' => 'United States', 'code' => 'US', 'flag' => '🇺🇸'],
        'GB' => ['name' => 'United Kingdom', 'code' => 'GB', 'flag' => '🇬🇧'],
    ]
    
  • Missing Countries: If a country is missing, check if it exists in the package’s source data (vendor/aheenam/countries/src/Countries/Countries.php).

Extension Points

  1. Custom Data Sources: Extend the Aheenam\Countries\Countries class to load from a database or external API:

    class CustomCountries extends Countries {
        public function all() {
            return Cache::remember('custom_countries', now()->addDays(1), function () {
                return DB::table('countries')->get()->keyBy('code');
            });
        }
    }
    

    Bind it in AppServiceProvider:

    $this->app->bind('Aheenam\Countries\Countries', function ($app) {
        return new CustomCountries();
    });
    
  2. Adding Fields: Merge additional data (e.g., phone_code) into the country array:

    $countries = Countries::all();
    foreach ($countries as &$country) {
        $country['phone_code'] = $this->getPhoneCode($country['code']);
    }
    
  3. Testing: Mock the facade in tests:

    Countries::shouldReceive('all')->andReturn([...]);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui