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

drnd-dev/laravel-countries

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require drnd-dev/laravel-countries
    php artisan vendor:publish --provider="DrndDev\Countries\CountriesServiceProvider"
    
    • Publishes the package's configuration and migrations (if any).
  2. First Use Case: Fetch a country by ISO code (e.g., US):

    use DrndDev\Countries\Facades\Countries;
    
    $country = Countries::get('US');
    // Returns: Country object with name, code, translations, coordinates, etc.
    
  3. Where to Look First:

    • Facade: DrndDev\Countries\Facades\Countries (primary entry point).
    • Documentation: Full Docs for API reference.
    • Config: Published at config/countries.php (e.g., default locale, data source).

Implementation Patterns

Core Workflows

  1. Fetching Countries:

    • Single Country:
      $country = Countries::get('GB'); // By ISO code
      $country = Countries::find(826); // By numeric code
      
    • All Countries:
      $countries = Countries::all(); // Collection of Country objects
      $countries = Countries::list(); // Array of [code => name] pairs
      
    • Filtered List:
      $europeanCountries = Countries::where('region', 'EU')->get();
      
  2. Multilingual Support:

    • Translate country names dynamically:
      $country->name('es'); // Spanish name
      $country->translations; // All available translations
      
    • Set default locale in config/countries.php:
      'default_locale' => 'en',
      
  3. Geographic Data:

    • Access coordinates or region:
      $latitude = $country->latitude;
      $region = $country->region; // e.g., 'Americas'
      
  4. Integration with Eloquent:

    • Attach country data to models:
      use DrndDev\Countries\Database\Traits\HasCountries;
      
      class User extends Model
      {
          use HasCountries;
      }
      // Automatically adds `country_id` column and accessors.
      
  5. Caching:

    • Enable caching in config to improve performance:
      'cache' => true,
      
    • Clear cache manually:
      php artisan countries:clear-cache
      

Advanced Patterns

  1. Custom Data Sources:

    • Extend the package to load from a custom JSON file:
      Countries::setDataSource(app_path('data/custom_countries.json'));
      
  2. API Responses:

    • Format country data for APIs:
      $response = Countries::get('CA')->toArray();
      // Returns: ['code' => 'CA', 'name' => 'Canada', ...]
      
  3. Validation:

    • Validate country codes in forms:
      use DrndDev\Countries\Rules\ValidCountry;
      
      $request->validate([
          'country' => ['required', new ValidCountry],
      ]);
      
  4. Events:

    • Listen for country-related events (e.g., CountryRetrieved):
      Countries::get('JP'); // Triggers events
      

Gotchas and Tips

Pitfalls

  1. Locale Mismatches:

    • If translations are missing for a locale, the package falls back to the default. Verify supported locales in config/countries.php:
      'supported_locales' => ['en', 'es', 'fr'],
      
  2. Caching Issues:

    • After updating the package, clear the cache:
      php artisan countries:clear-cache
      
    • Disable caching during development if data changes frequently.
  3. Database vs. In-Memory:

    • The package defaults to in-memory storage. For large-scale apps, consider storing country data in a database table and extending the CountryRepository interface.
  4. Numeric vs. ISO Codes:

    • Some methods use numeric codes (e.g., 826 for Canada), while others use ISO (CA). Double-check the expected format in the method signature.
  5. Migration Conflicts:

    • If publishing migrations, ensure they don’t conflict with existing countries tables in your app.

Debugging Tips

  1. Log Country Data:

    \Log::info('Country data:', ['data' => Countries::get('DE')->toArray()]);
    
  2. Check Data Source:

    • Verify the data source path in config/countries.php:
      'data_source' => database_path('countries.json'),
      
  3. Validate ISO Codes:

    • Use the isValidIsoCode() helper:
      if (!Countries::isValidIsoCode('XX')) {
          // Handle invalid code
      }
      

Extension Points

  1. Custom Fields:

    • Extend the Country model to add custom attributes:
      class CustomCountry extends \DrndDev\Countries\Models\Country
      {
          protected $appends = ['custom_field'];
      }
      
  2. Override Data:

    • Replace the default data source by binding a custom repository:
      $this->app->bind(
          \DrndDev\Countries\Contracts\CountryRepository::class,
          \App\Repositories\CustomCountryRepository::class
      );
      
  3. Add New Locales:

    • Extend the Country model to support additional translations:
      public function name($locale = null)
      {
          $locale = $locale ?: config('countries.default_locale');
          return $this->translations[$locale] ?? parent::name($locale);
      }
      
  4. Testing:

    • Mock the Countries facade in tests:
      $this->mock(Countries::class)->shouldReceive('get')->andReturn($mockCountry);
      
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai