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

lwwcas/laravel-countries

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require lwwcas/laravel-countries
    php artisan vendor:publish --provider="Lwwcas\Countries\CountriesServiceProvider" --tag="countries-config"
    
    • Publishes the default configuration and language files to config/countries.php and resources/lang/.
  2. First Use Case: Fetch all countries with their default names:

    use Lwwcas\Countries\Facades\Countries;
    
    $countries = Countries::all(); // Collection of Country models
    $firstCountry = Countries::first(); // First country in the list
    
  3. Basic Querying:

    // Get a country by ISO code
    $country = Countries::find('US');
    
    // Get countries by continent
    $europeanCountries = Countries::where('continent', 'Europe')->get();
    
  4. Multilingual Support:

    // Set language (e.g., for Spanish)
    app()->setLocale('es');
    $countryName = Countries::find('ES')->name; // Returns "España"
    

Implementation Patterns

Core Workflows

  1. Country Data Retrieval:

    • Eager Loading: Use with() to load related data (e.g., currencies, languages):
      $country = Countries::with('currencies', 'languages')->find('CA');
      
    • Chunking: Process large datasets efficiently:
      Countries::chunk(100, function ($countries) {
          foreach ($countries as $country) {
              // Process each country
          }
      });
      
  2. Filtering and Searching:

    • Dynamic Queries: Leverage Laravel's query builder:
      $results = Countries::where('name', 'like', '%France%')
                          ->orWhere('iso2', 'FR')
                          ->get();
      
    • Custom Attributes: Filter by custom fields (e.g., calling_code):
      $countries = Countries::where('calling_code', '1')->get(); // North America
      
  3. Integration with Eloquent Models:

    • Polymorphic Relationships: Attach countries to models:
      // In a User model
      public function country()
      {
          return $this->morphTo();
      }
      
      // Store a country on a user
      $user->country()->associate(Countries::find('JP'));
      $user->save();
      
  4. Localization:

    • Language Switching: Dynamically change language in runtime:
      Countries::setLocale('fr'); // Override app locale for this request
      $countryName = Countries::find('DE')->name; // "Allemagne"
      
    • Fallback Languages: Configure in config/countries.php:
      'locales' => [
          'default' => 'en',
          'fallback' => ['en', 'es'],
      ],
      
  5. Geospatial Queries:

    • Distance Calculations: Use coordinates for proximity searches:
      $nearbyCountries = Countries::whereBetween('latitude', [40, 50])
                                  ->whereBetween('longitude', [-10, 10])
                                  ->get();
      

Advanced Patterns

  1. Caching:

    • Cache country lists or specific queries:
      $countries = Cache::remember('all_countries', now()->addHours(1), function () {
          return Countries::all();
      });
      
  2. API Integration:

    • Fetch real-time updates from external APIs (e.g., RESTCountries):
      // Example: Sync with an external API
      $externalData = Http::get('https://restcountries.com/v3.1/all');
      Countries::syncFromExternal($externalData);
      
  3. Custom Collections:

    • Extend the base collection for domain-specific logic:
      use Lwwcas\Countries\Country;
      
      $customCollection = collect(Countries::all())
          ->map(fn (Country $country) => [
              'id' => $country->iso3,
              'label' => $country->name,
          ]);
      
  4. Validation Rules:

    • Use the package in Form Requests:
      use Lwwcas\Countries\Rules\ValidCountry;
      
      public function rules()
      {
          return [
              'country_code' => ['required', new ValidCountry],
          ];
      }
      
  5. Event Listeners:

    • Trigger actions on country-related events (e.g., CountryRetrieved):
      // In EventServiceProvider
      protected $listen = [
          \Lwwcas\Countries\Events\CountryRetrieved::class => [
              \App\Listeners\LogCountryAccess::class,
          ],
      ];
      

Gotchas and Tips

Common Pitfalls

  1. Locale Mismatches:

    • Issue: Names not translating as expected.
    • Fix: Ensure the language files are published and the app locale is set correctly:
      php artisan vendor:publish --tag="countries-lang"
      
      Verify config/countries.php has the correct locales array.
  2. Case Sensitivity in ISO Codes:

    • Issue: Countries::find('us') returns null (ISO codes are uppercase).
    • Fix: Normalize input:
      $country = Countries::find(strtoupper($userInput));
      
  3. Missing Data:

    • Issue: Some countries lack certain fields (e.g., region).
    • Fix: Use fillMissing() to provide defaults:
      $country = Countries::find('BV')->fillMissing([
          'region' => 'Antarctica',
      ]);
      
  4. Performance with Large Datasets:

    • Issue: Slow queries when fetching all countries.
    • Fix: Cache aggressively or use pagination:
      $countries = Countries::paginate(50);
      
  5. Timezone Confusion:

    • Issue: Coordinates or timezones appear incorrect.
    • Fix: Validate data against a trusted source (e.g., GeoNames API) or use the package's built-in validation:
      $country = Countries::find('AU')->validateCoordinates();
      

Debugging Tips

  1. Inspect Raw Data:

    • Dump the underlying data structure:
      dd(Countries::getRawData());
      
  2. Check Published Config:

    • Override defaults in config/countries.php:
      'enabled' => env('COUNTRIES_ENABLED', true),
      'cache_driver' => env('COUNTRIES_CACHE_DRIVER', 'array'),
      
  3. Enable Query Logging:

    • Debug slow queries:
      \DB::enableQueryLog();
      $countries = Countries::all();
      dd(\DB::getQueryLog());
      
  4. Validate ISO Codes:

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

Extension Points

  1. Custom Fields:

    • Add new attributes via a model observer or accessor:
      // In Country model
      public function getFullNameAttribute()
      {
          return "{$this->name} ({$this->iso3})";
      }
      
  2. Override Data Sources:

    • Replace the default data source by binding a new implementation:
      $this->app->bind(\Lwwcas\Countries\Contracts\CountryDataSource::class, function () {
          return new \App\Services\CustomCountryDataSource;
      });
      
  3. Add New Languages:

    • Publish and extend language files:
      php artisan vendor:publish --tag="countries-lang" --force
      
      Add translations to resources/lang/{locale}/countries.php.
  4. Hook into Data Loading:

    • Extend the Country model to modify data on retrieval:
      protected static function boot()
      {
          parent::boot();
          static::retrieved(function ($country) {
              $country->setAttribute('custom_field', 'value');
          });
      }
      
  5. Create Custom Query Scopes:

    • Add reusable scopes to the Country model:
      public function scopeByRegion($query, $region)
      {
          return $query->where('region', $region);
      }
      
      Usage:
      $countries = Countries::byRegion('Europe')->get();
      

Configuration Quirks

  1. Cache Driver:

    • Ensure the cache driver in config/countries.php matches your .env:
      'cache_driver' => env('COUNTRIES_CACHE_DRIVER', 'file'),
      
    • Supported drivers: array, file, database, redis, etc.
  2. Data Syncing:

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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
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