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 Id Countries Laravel Package

ferdirn/laravel-id-countries

Laravel package to create and seed a countries table with global country data: name, ISO code, capital, currency, and calling code. Includes artisan commands to generate migrations and a seeder for quick setup in your app.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require ferdirn/laravel-id-countries
    

    Add the service provider and facade to config/app.php:

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

    php artisan vendor:publish --provider="Ferdirn\Countries\CountriesServiceProvider"
    

    (Only if you need to customize the default countries table name.)

  3. Run Migrations:

    php artisan migrate
    

    The package creates a countries table with columns: id, name, iso_code, capital, currency, calling_code.

  4. First Use Case: Fetch all countries in a controller or blade view:

    use Countries;
    
    $countries = Countries::all();
    return view('countries.index', compact('countries'));
    

Implementation Patterns

Common Workflows

  1. Fetching Countries:

    • All Countries:
      $countries = Countries::all(); // Collection of Country models
      
    • Single Country by ISO Code:
      $country = Countries::where('iso_code', 'US')->first();
      
    • Search by Name:
      $countries = Countries::where('name', 'like', '%United%')->get();
      
  2. Integration with Eloquent Models: Use polymorphic relationships or foreign keys to link countries to other models (e.g., users table):

    // In User model
    public function country()
    {
        return $this->belongsTo(Country::class);
    }
    

    Query users by country:

    $usersInUs = User::whereHas('country', function($query) {
        $query->where('iso_code', 'US');
    })->get();
    
  3. Blade Views: Render a dropdown of countries:

    <select name="country_id">
        @foreach(Countries::all() as $country)
            <option value="{{ $country->id }}">{{ $country->name }} ({{ $country->iso_code }})</option>
        @endforeach
    </select>
    
  4. API Responses: Return countries as JSON in a controller:

    return Countries::select('id', 'name', 'iso_code')->get();
    
  5. Caching: Cache the countries list to reduce database queries (e.g., in AppServiceProvider):

    public function boot()
    {
        Cache::remember('countries', now()->addHours(1), function() {
            return Countries::all();
        });
    }
    

Gotchas and Tips

Pitfalls

  1. Table Name Assumption:

    • The package defaults to countries table. If you rename it via config, ensure migrations and queries reflect this change.
    • Fix: Always verify the table name in config/countries.php (if published) or check the migration file.
  2. Missing Facade Alias:

    • Forgetting to add the facade alias ('Countries' => 'Ferdirn\Countries\CountriesFacade') will throw Class not found errors.
    • Fix: Recheck config/app.php after installation.
  3. Case Sensitivity in ISO Codes:

    • ISO codes (e.g., US, us) are case-sensitive in queries. Use strtoupper() for consistency:
      $country = Countries::where('iso_code', strtoupper('us'))->first();
      
  4. Migration Conflicts:

    • If the countries table already exists, the migration may fail. The package does not handle this gracefully.
    • Fix: Manually drop the table or modify the migration file before running php artisan migrate.
  5. Data Updates:

    • The package does not provide a built-in way to update country data. For dynamic updates, consider:
      • Writing a custom seeder or job to sync with an external API (e.g., REST Countries).
      • Using a package like spatie/laravel-data-import to manually update records.

Debugging Tips

  1. Check Published Config: If the package behaves unexpectedly, verify config/countries.php exists and matches your expectations:

    php artisan config:clear
    
  2. Query Logging: Enable Laravel's query log to debug slow or failing queries:

    DB::enableQueryLog();
    $countries = Countries::all();
    dd(DB::getQueryLog());
    
  3. Model Binding Issues: If Countries::find($id) returns null, ensure:

    • The id column is auto-incrementing and primary in the countries table.
    • The Country model is properly namespaced (e.g., Ferdirn\Countries\Models\Country).

Extension Points

  1. Custom Fields: Extend the Country model to add custom fields (e.g., region, population):

    // In Country model
    protected $fillable = ['name', 'iso_code', 'capital', 'currency', 'calling_code', 'region'];
    

    Update the migration and seeder accordingly.

  2. Localization: Add translated country names using Laravel's localization features:

    // In Country model
    public function getNameAttribute($value)
    {
        return trans('countries.' . $this->iso_code);
    }
    

    Define translations in resources/lang/{locale}/countries.php.

  3. API Integration: Sync country data with an external API (e.g., REST Countries):

    // Example seeder
    public function run()
    {
        $response = Http::get('https://restcountries.com/v3.1/all');
        foreach ($response->json() as $country) {
            Country::updateOrCreate(
                ['iso_code' => $country['cca2']],
                [
                    'name' => $country['name']['common'],
                    'capital' => $country['capital'][0] ?? null,
                    'currency' => $country['currencies'][0]['name'] ?? null,
                    'calling_code' => $country['idd']['root'] . $country['idd']['suffixes'][0] ?? null,
                ]
            );
        }
    }
    
  4. Validation Rules: Create custom validation rules for country-related fields:

    use Illuminate\Validation\Rule;
    
    $validated = request()->validate([
        'country_iso_code' => [
            'required',
            Rule::exists('countries', 'iso_code'),
        ],
    ]);
    
  5. Scopes: Add reusable query scopes to the Country model:

    // In Country model
    public function scopeByRegion($query, $region)
    {
        return $query->where('region', $region);
    }
    

    Usage:

    $europeanCountries = Countries::byRegion('Europe')->get();
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui