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

aaix/laravel-countries

Modern Laravel country-data package with zero-touch install, auto-loaded migrations, and idempotent seeders to keep tables and rows in sync on every deploy. Includes regions, countries, language translations, and native_name. Compatible with lwwcas schema/models.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require aaix/laravel-countries
    php artisan migrate
    
    • The package auto-loads a countries table via migrations. No additional commands or configurations are needed.
  2. First Use Case:

    • Fetching a Country by ISO Code:
      use Aaix\Countries\Facades\Countries;
      
      $country = Countries::get('US'); // Returns country data for the United States
      
    • Fetching All Countries:
      $allCountries = Countries::all(); // Returns a collection of all countries
      
  3. Where to Look First:

    • Facade API: Aaix\Countries\Facades\Countries for quick access.
    • Eloquent Model: \Aaix\Countries\Models\Country for direct database interactions.
    • Migrations: database/migrations/[timestamp]_create_countries_table.php to inspect the schema.

Implementation Patterns

Usage Patterns

  1. Basic Data Retrieval:

    • Use the facade for simplicity:
      $countryName = Countries::get('GB')->name; // "United Kingdom"
      $countryCode = Countries::get('JP')->iso2; // "JP"
      
  2. Filtering Countries:

    • Filter by region or other attributes:
      $europeanCountries = Countries::all()->where('region', 'Europe');
      
  3. Integration with Forms:

    • Use the iso2 or iso3 fields for dropdowns or validation:
      use Illuminate\Support\Facades\Validator;
      
      $validator = Validator::make($request->all(), [
          'country' => 'required|exists:countries,iso2',
      ]);
      
  4. Seeding Custom Data:

    • Extend the Country model or use the seeder directly:
      use Aaix\Countries\Database\Seeders\CountriesTableSeeder;
      
      // Manually trigger seeder (if needed)
      $this->call(CountriesTableSeeder::class);
      
  5. Localization:

    • The package includes localized names (e.g., name_en, name_es). Access them via:
      $country = Countries::get('FR');
      $nameInSpanish = $country->name_es; // "Francia"
      

Workflows

  1. Zero-Touch Setup:

    • No interactive commands or manual configurations. Install, migrate, and use.
  2. Idempotent Seeders:

    • Safe to run migrations repeatedly without data duplication.
  3. API-Driven Development:

    • Prefer the facade for most use cases. Fall back to Eloquent for complex queries:
      $countries = \Aaix\Countries\Models\Country::where('region', 'Asia')->get();
      
  4. Testing:

    • Use the facade in tests for clean, readable assertions:
      $this->assertEquals('Canada', Countries::get('CA')->name);
      

Integration Tips

  1. Laravel Scout:

    • Index the countries table for search functionality:
      use Laravel\Scout\Searchable;
      
      class Country extends \Aaix\Countries\Models\Country
      {
          use Searchable;
      }
      
  2. API Responses:

    • Normalize country data in API responses:
      return response()->json([
          'country' => Countries::get($request->country)->toArray(),
      ]);
      
  3. Blade Templates:

    • Loop through countries in views:
      @foreach (Countries::all() as $country)
          <option value="{{ $country->iso2 }}">{{ $country->name }}</option>
      @endforeach
      
  4. Caching:

    • Cache frequent queries (e.g., all countries):
      $countries = Cache::remember('all-countries', now()->addDays(7), function () {
          return Countries::all();
      });
      

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • If you manually create a countries table, drop it before running migrations to avoid conflicts. The package’s migration is idempotent but assumes a fresh table.
  2. Locale Fallbacks:

    • If a locale (e.g., name_es) is missing, the package defaults to name_en. Handle missing locales explicitly if needed:
      $name = $country->{'name_' . $locale} ?? $country->name_en;
      
  3. Performance with Large Queries:

    • Avoid eager-loading all countries in a single request. Use pagination or lazy loading:
      $countries = Countries::all()->paginate(20);
      
  4. Overwriting Default Data:

    • The seeder is opinionated. To customize, extend the Country model or create a custom seeder that updates specific fields.

Debugging

  1. Missing Data:

    • Verify the countries table exists and is populated:
      php artisan migrate:fresh --seed
      
    • Check for errors in storage/logs/laravel.log if seeding fails.
  2. Facade Not Found:

    • Ensure the service provider is registered (it is by default). If using Laravel < 5.5, manually add to config/app.php:
      'providers' => [
          // ...
          Aaix\Countries\CountriesServiceProvider::class,
      ],
      
  3. Locale-Specific Issues:

    • Confirm the locale code matches the package’s conventions (e.g., en, es). Refer to the supported locales.

Tips

  1. Custom Fields:

    • Add custom fields to the countries table via a new migration:
      Schema::table('countries', function (Blueprint $table) {
          $table->string('custom_field')->nullable();
      });
      
    • Update the seeder or model to handle the new field.
  2. Partial Updates:

    • Use the updateOrCreate method to patch country data:
      \Aaix\Countries\Models\Country::updateOrCreate(
          ['iso2' => 'US'],
          ['custom_field' => 'value']
      );
      
  3. Testing Seeders:

    • Reset the database and seed in tests:
      public function setUp(): void
      {
          parent::setUp();
          Artisan::call('migrate:fresh', ['--seed' => true]);
      }
      
  4. Extending the Facade:

    • Add custom methods to the facade by extending it:
      namespace App\Facades;
      
      use Aaix\Countries\Facades\Countries as BaseCountries;
      use Illuminate\Support\Facades\Facade;
      
      class Countries extends Facade
      {
          protected static function getFacadeAccessor()
          {
              return 'countries';
          }
      
          public static function getByRegion($region)
          {
              return BaseCountries::all()->where('region', $region);
          }
      }
      
    • Bind the new facade in AppServiceProvider.
  5. Performance Optimization:

    • Add indexes to frequently queried columns:
      Schema::table('countries', function (Blueprint $table) {
          $table->index('iso2');
          $table->index('iso3');
          $table->index('region');
      });
      
  6. Fallback to Original Package:

    • If issues arise, compare with the original package for differences in behavior or features.
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