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

webpatser/laravel-countries

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation:

    composer require webpatser/laravel-countries
    php artisan countries:install
    
    • The install command publishes the database table and migrations (if using the Eloquent model feature).
  2. Basic Usage:

    use Webpatser\Countries\Countries;
    
    $countries = new Countries();
    
    • Initialize the Countries facade or class in your controller/service.
  3. First Use Case: Fetch a country by ISO code (e.g., for a user profile form):

    $country = Countries::getOne('US');
    return view('profile', ['country' => $country]);
    

Where to Look First

  • Facade: Countries::getOne(), Countries::getList(), Countries::getByCurrency().
  • Validation: use Webpatser\Countries\Rules\Country; for form validation.
  • Collection Macros: Extend Laravel Collections with country-specific methods (e.g., countryName()).

Implementation Patterns

Common Workflows

  1. Country Selection in Forms:

    // Blade template
    <select name="country">
        @foreach (Countries::getList() as $country)
            <option value="{{ $country->iso2 }}">{{ $country->name }}</option>
        @endforeach
    </select>
    
    • Use Countries::getList() to populate dropdowns dynamically.
  2. Filtering Countries by Region/Currency:

    // Get all EU countries
    $euCountries = Countries::getByRegion('EU');
    
    // Get countries using EUR
    $eurCountries = Countries::getByCurrency('EUR');
    
    • Ideal for multi-step forms (e.g., "Select your region first").
  3. Validation:

    use Webpatser\Countries\Rules\Country;
    
    $request->validate([
        'country' => ['required', new Country],
    ]);
    
    • Validate ISO codes (e.g., US, DE) or country names.
  4. Eloquent Model Integration:

    use Webpatser\Countries\HasCountries;
    
    class User extends Model
    {
        use HasCountries;
    }
    
    • Attach country data to models (e.g., user->country returns a Country object).
  5. Collection Macros:

    // Add a macro to get country names from a collection of users
    Collect::macro('countryNames', function () {
        return $this->pluck('country')->map(fn ($country) => $country->name);
    });
    
    // Usage
    $names = User::all()->countryNames();
    

Integration Tips

  • Caching: Cache Countries::getList() if performance is critical (e.g., in a high-traffic app):
    $countries = Cache::remember('all-countries', now()->addDays(7), function () {
        return Countries::getList();
    });
    
  • Localization: Override country names via language files (resources/lang/en/countries.php).
  • API Responses: Serialize country data in API responses:
    return response()->json([
        'country' => Countries::getOne($request->country)->toArray(),
    ]);
    

Gotchas and Tips

Pitfalls

  1. Database vs. In-Memory:

    • The package defaults to in-memory storage. If using the Eloquent model (HasCountries), run migrations after countries:install:
      php artisan migrate
      
    • Gotcha: Forgetting to migrate can cause HasCountries to fail silently.
  2. ISO Code Case Sensitivity:

    • ISO codes (e.g., US, us) are case-sensitive in Countries::getOne(). Always use uppercase:
      // Correct
      $usa = Countries::getOne('US');
      
      // Fails silently (returns null)
      $usa = Countries::getOne('us');
      
  3. Collection Macros Overwriting:

    • If you add a macro named country() or name(), it may conflict with existing methods. Use unique names:
      Collect::macro('countryNames', function () { ... });
      
  4. Flag Emoji Rendering:

    • Flag emojis (e.g., 🇺🇸) may not display correctly in all environments. Test in production early.

Debugging

  • Missing Data:
    • Verify the countries table exists (if using Eloquent) or check the in-memory data structure:
      dd(Countries::getList()->first()->toArray());
      
  • Validation Errors:
    • Ensure the Country rule is imported correctly. Common typo: use Webpatser\Countries\Rule\Country; (missing s).

Extension Points

  1. Custom Fields:

    • Extend the Country model to add custom attributes:
      class Country extends \Webpatser\Countries\Country
      {
          public function getPhoneCodeAttribute()
          {
              return $this->attributes['phone_code'] ?? '+1'; // Example
          }
      }
      
    • Override the Countries service provider to modify the model.
  2. Additional Data Sources:

    • Merge with external APIs (e.g., for real-time updates):
      $countries = Countries::getList()->merge($externalApiData);
      
  3. Testing:

    • Mock the Countries facade in tests:
      $this->mock(Countries::class, function ($mock) {
          $mock->shouldReceive('getOne')->andReturn(new Country(['iso2' => 'US']));
      });
      
  4. Performance:

    • For large datasets, lazy-load regions/currencies:
      $countries->getList()->load('regions', 'currency');
      
    • Note: The package doesn’t support eager loading by default; use with() on the underlying query if using Eloquent.

Config Quirks

  • Published Config:

    • The package doesn’t publish a config file by default, but you can publish it manually:
      php artisan vendor:publish --provider="Webpatser\Countries\CountriesServiceProvider"
      
    • Customize default behavior (e.g., enable/disable flag emojis) in config/countries.php.
  • Language Fallback:

    • If a country name isn’t found in the current language, it falls back to English. Override in app/Providers/AppServiceProvider:
      Countries::setFallbackLanguage('es');
      
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