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

Native Country Names Laravel Package

laravel-lang/native-country-names

Provides native-language country names for Laravel apps. Install via composer and use localized datasets to display countries in their own languages. Maintained by Laravel Lang; MIT licensed.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:
    composer require laravel-lang/native-country-names
    
  2. Publish the configuration (optional, for customization):
    php artisan vendor:publish --provider="LaravelLang\CountryNames\CountryNamesServiceProvider"
    
  3. First Use Case: Display a country name in the current app locale:
    use LaravelLang\CountryNames\Country;
    
    $countryName = Country::name('US'); // Returns 'United States' (en) or localized equivalent
    

Where to Look First


Implementation Patterns

Core Workflows

1. Dynamic Country Name Resolution

// In Blade templates
<select name="country">
    @foreach (Country::all() as $code => $name)
        <option value="{{ $code }}">{{ $name }}</option>
    @endforeach
</select>
  • Pattern: Use Country::all() to generate localized dropdowns.
  • Tip: Cache the result if performance is critical (e.g., in a high-traffic checkout flow).

2. Locale-Aware API Responses

// In controllers/APIs
return response()->json([
    'countries' => Country::all($request->locale)
]);
  • Pattern: Pass the user’s locale (e.g., from app()->getLocale() or request) to Country::all() or Country::name().
  • Integration Tip: Use middleware to set the locale dynamically (e.g., Accept-Language header).

3. Fallback Logic for Missing Locales

$name = Country::name('US', 'fr', 'en'); // 'États-Unis' (fr) or 'United States' (en fallback)
  • Pattern: Chain fallback locales to ensure graceful degradation.

4. CLI/Artisan Commands

// In console commands
$countries = Country::all('es');
foreach ($countries as $code => $name) {
    $this->info("{$code}: {$name}");
}
  • Use Case: Generate localized reports or seed databases.

5. Testing

use LaravelLang\CountryNames\Tests\TestCase;

public function testCountryNames()
{
    $this->assertEquals('Deutschland', Country::name('DE', 'de'));
    $this->assertEquals('Germany', Country::name('DE', 'en'));
}
  • Pattern: Extend TestCase for locale-specific assertions.

Advanced Patterns

Custom Data Sources

Override the default dataset by publishing the config and updating the data_path:

// config/country-names.php
'data_path' => database_path('countries.json'),
  • Use Case: Extend with internal codes or non-ISO names.

Caching Layer

Cache country data for performance:

$countries = Cache::remember('countries_'.$locale, now()->addHours(1), function() use ($locale) {
    return Country::all($locale);
});
  • Tip: Invalidate cache on locale changes or data updates.

Integration with Laravel Lang

Combine with other Laravel Lang packages (e.g., laravel-lang/iso-3166) for richer country data:

use LaravelLang\ISO3166\ISO3166;

$country = ISO3166::where('alpha2', 'US')->first();
$name = Country::name($country->alpha2);

Gotchas and Tips

Pitfalls

  1. Locale Mismatches

    • Issue: Country::name('US') defaults to the app’s locale. If the app locale isn’t set, it may return unexpected results.
    • Fix: Explicitly pass the locale:
      Country::name('US', 'fr'); // Force French
      
  2. Data Updates

    • Issue: The package updates data via GitHub Actions. If you fork the package, you’ll need to manually update the dataset.
    • Fix: Monitor release notes or use the update:data Artisan command (if available in future versions).
  3. Case Sensitivity

    • Issue: Country codes (e.g., US vs. us) are case-insensitive, but some integrations may enforce uppercase.
    • Fix: Normalize codes:
      $code = strtoupper($userInput);
      
  4. Missing Locales

    • Issue: Not all locales have translations for every country (e.g., rare languages or newly recognized states).
    • Fix: Use fallback locales or handle exceptions:
      try {
          $name = Country::name('XK', 'sq'); // Kosovo (Albanian)
      } catch (\InvalidArgumentException $e) {
          $name = Country::name('XK', 'en'); // Fallback to English
      }
      
  5. Performance with Large Datasets

    • Issue: Loading all countries (Country::all()) may impact performance in memory-constrained environments.
    • Fix: Lazy-load or paginate:
      $countries = collect(Country::all())->take(50);
      

Debugging Tips

  • Verify Locales: Check supported locales with:
    dd(Country::getSupportedLocales());
    
  • Inspect Data: Dump the raw dataset for a locale:
    dd(Country::getData('es'));
    
  • Check for Typos: Country codes must match ISO 3166-1 alpha-2 (e.g., US, not USA).

Extension Points

  1. Add Custom Countries Extend the dataset by publishing the config and merging custom data:

    // config/country-names.php
    'custom_data' => [
        'XX' => [
            'en' => 'Custom Land',
            'es' => 'Tierra Personalizada',
        ],
    ],
    
  2. Override Facade Methods Bind a custom class to the Country facade in AppServiceProvider:

    use LaravelLang\CountryNames\Facades\Country;
    
    Country::swap(new \App\Services\CustomCountryService());
    
  3. Localization Hooks Use Laravel’s locale.booted event to dynamically set country names:

    Event::listen('locale.booted', function ($locale) {
        app('translator')->setLocale($locale);
        // Custom logic for locale-specific country names
    });
    
  4. Testing Edge Cases Write tests for:

    • Unsupported locales/countries.
    • Locale fallbacks.
    • Case-insensitive codes.

Configuration Quirks

  • Default Locale: The package respects Laravel’s default locale (config/app.php). Override it per request if needed:
    app()->setLocale('fr');
    
  • Data Path: The default path is vendor/laravel-lang/native-country-names/data/. Avoid modifying this directory directly; use the config override instead.

Pro Tips

  • Combine with Laravel Jetstream: Localize country dropdowns in user profiles:
    <x-jet-label for="country" value="{{ __('Country') }}" />
    <x-jet-input id="country" type="text" list="countries" />
    <datalist id="countries">
        @foreach (Country::all() as $code => $name)
            <option value="{{ $name }} ({{ $code }})">
        @endforeach
    </datalist>
    
  • API-First Approach: Expose country names via a dedicated endpoint:
    Route::get('/api/countries', function (Request $request) {
        return Country::all($request->locale);
    });
    
  • Localization Testing: Use Laravel’s LocaleMiddleware to test multiple locales in a single request:
    $response = $this->withHeaders(['Accept-Language' => 'fr'])
        ->get('/countries');
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport