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

Laravel Countries Laravel Package

yayann/laravel-countries

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require webpatser/laravel-countries
    

    Update config/app.php to include:

    'providers' => [
        Webpatser\Countries\CountriesServiceProvider::class,
    ],
    'aliases' => [
        'Countries' => Webpatser\Countries\CountriesFacade::class,
    ]
    
  2. Publish Configuration (Optional):

    php artisan config:publish webpatser/laravel-countries
    

    (Only needed if customizing the countries table name.)

  3. Run Migration:

    php artisan countries:migration
    php artisan migrate
    
  4. First Use Case: Fetch a country by ISO code:

    $country = Countries::get('US');
    dd($country->name); // Outputs: "United States"
    

Implementation Patterns

Core Workflows

  1. Retrieving Country Data:

    // By ISO code (2-letter)
    $country = Countries::get('US');
    
    // By ISO 3166-1 numeric code
    $country = Countries::getByNumeric('840');
    
    // All countries (as collection)
    $allCountries = Countries::all();
    
  2. Filtering Countries:

    // By continent
    $europeanCountries = Countries::where('continent', 'Europe')->get();
    
    // By currency
    $euroCountries = Countries::where('currency', 'EUR')->get();
    
  3. Integration with Eloquent Models: Add a country_id field to a model (e.g., User) and use the facade:

    // In a User model
    public function country()
    {
        return $this->belongsTo(Country::class);
    }
    
    // Usage
    $user = User::find(1);
    $countryName = $user->country->name; // "Canada" if country_id=124
    
  4. Form Validation:

    use Webpatser\Countries\Rules\Country;
    
    $request->validate([
        'country_code' => ['required', new Country],
    ]);
    
  5. Localization: Publish translations (if needed):

    php artisan vendor:publish --provider="Webpatser\Countries\CountriesServiceProvider" --tag=lang
    

    Then use:

    $countryName = __("countries.US"); // "United States" (if translated)
    

Advanced Patterns

  1. Custom Queries: Extend the Country model to add scopes:

    // In app/Providers/AppServiceProvider.php
    use Webpatser\Countries\Models\Country;
    
    Country::addGlobalScope('Active', function (Builder $builder) {
        $builder->where('active', 1);
    });
    
  2. API Responses: Format country data for APIs:

    return response()->json([
        'country' => Countries::get('US')->toArray(),
    ]);
    
  3. Caching: Cache country data for performance:

    $countries = Cache::remember('all-countries', now()->addDays(7), function () {
        return Countries::all();
    });
    

Gotchas and Tips

Pitfalls

  1. Outdated Data:

    • The package was last updated in 2015. Verify ISO codes (e.g., SSD for South Sudan) or currencies (e.g., EUR for new EU members) manually if critical.
    • Workaround: Override the countries table with a custom migration or use a modern alternative like league/iso3166.
  2. Missing ISO 3166-2 Codes:

    • The package claims "Almost ISO 3166-2" support. Some regions (e.g., overseas territories) may lack sub-division data.
    • Tip: Cross-reference with GeoNames or ISO Online Browsing Platform.
  3. Facade vs. Model Direct Access:

    • Prefer Countries::get('US') for simplicity, but access the underlying Country model directly for complex queries:
      $country = \Webpatser\Countries\Models\Country::where('iso', 'US')->first();
      
  4. Migration Conflicts:

    • If the countries table already exists, drop it first or use:
      php artisan countries:migration --force
      

Debugging Tips

  1. Check Database Data:

    php artisan tinker
    >>> \Webpatser\Countries\Models\Country::all()->count(); // Should return 249 (as of 2015)
    
  2. Validate ISO Codes:

    if (!Countries::exists('XX')) { // 'XX' = invalid code
        abort(400, 'Invalid country code');
    }
    
  3. Override Defaults: Publish and modify the config:

    php artisan config:publish webpatser/laravel-countries
    

    Then update config/countries.php (e.g., change table or model values).


Extension Points

  1. Add Custom Fields: Extend the Country model:

    // app/Models/Country.php
    namespace App\Models;
    use Webpatser\Countries\Models\Country as BaseCountry;
    
    class Country extends BaseCountry
    {
        protected $appends = ['population_density'];
        public function getPopulationDensityAttribute()
        {
            return $this->population / ($this->area ?? 1);
        }
    }
    
  2. Hook into Bootstrapping: Add logic in CountriesServiceProvider:

    // app/Providers/CountriesServiceProvider.php
    public function boot()
    {
        \Webpatser\Countries\Models\Country::created(function ($country) {
            // Log or notify when countries are added
        });
    }
    
  3. Replace the Data Source: Override the getCountries() method in the service provider to fetch from an external API:

    public function getCountries()
    {
        $response = Http::get('https://restcountries.com/v3.1/all');
        return collect($response->json())->map(fn ($data) => [
            'iso' => $data['cca2'],
            'name' => $data['name']['common'],
            // ... map other fields
        ]);
    }
    

Performance Notes

  • Eager Loading: Avoid N+1 queries when fetching related models:
    $users = User::with('country')->get();
    
  • Selective Fields: Limit columns fetched:
    $country = Countries::select('name', 'iso', 'currency')->get('US');
    
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