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

Laravel package providing country names in their native languages for localized UIs and forms. Part of the Laravel Lang ecosystem, install via Composer and use alongside your app’s localization setup. 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 Configuration (Optional):

    php artisan vendor:publish --provider="LaravelLang\NativeCountryNames\ServiceProvider"
    
    • Publishes config/native-country-names.php for customization (e.g., default locale, caching).
  3. First Use Case: Display a country name in the current app locale:

    use LaravelLang\NativeCountryNames\Facades\Country;
    
    // In a Blade template or controller
    $countryName = Country::name('US'); // Returns 'United States' (en) or 'États-Unis' (fr)
    
  4. Locale Switching:

    Country::setLocale('es'); // Force Spanish locale
    Country::name('US'); // 'Estados Unidos'
    
  5. Fetch All Countries:

    $countries = Country::all(); // Array of { code => name } pairs
    

Where to Look First


Implementation Patterns

Core Workflows

1. Dynamic Country Dropdowns

Use Case: Localized country selectors in forms (e.g., user profiles, checkout).

// Controller
public function editProfile()
{
    $countries = Country::all();
    return view('profile.edit', compact('countries'));
}
<select name="country">
    @foreach ($countries as $code => $name)
        <option value="{{ $code }}">{{ $name }}</option>
    @endforeach
</select>

Optimization: Cache the Country::all() result if the list rarely changes:

$countries = Cache::remember('native_countries', now()->addDays(7), fn() => Country::all());

2. API Responses with Localized Names

Use Case: Return country names in the user’s preferred language via API.

// API Endpoint
public function getCountries(Request $request)
{
    $locale = $request->header('Accept-Language') ?? app()->getLocale();
    Country::setLocale($locale);
    return Country::all();
}

Frontend Integration:

// Fetch and display in Vue/React
fetch('/api/countries')
  .then(res => res.json())
  .then(countries => {
    Object.entries(countries).forEach(([code, name]) => {
      document.querySelector(`option[value="${code}"]`).textContent = name;
    });
  });

3. Form Validation with Localized Messages

Use Case: Display validation errors in the user’s locale.

use Illuminate\Validation\Rule;

$validated = request()->validate([
    'country' => [
        'required',
        Rule::in(Country::all()->keys()),
        function ($attribute, $value, $fail) {
            $name = Country::name($value);
            $fail("Invalid country: {$name}.");
        },
    ],
]);

4. Fallback Locales

Use Case: Gracefully handle unsupported locales (e.g., user selects lg for Ligurian).

try {
    Country::setLocale('lg'); // Ligurian (unsupported)
    $name = Country::name('IT');
} catch (\InvalidArgumentException $e) {
    Country::setLocale('it'); // Fallback to Italian
    $name = Country::name('IT');
}

5. Integration with Laravel Lang Packages

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

use LaravelLang\ISO3166\ISO3166;
use LaravelLang\NativeCountryNames\Facades\Country;

$countryCode = 'US';
$countryName = Country::name($countryCode);
$region = ISO3166::get($countryCode)->region; // 'North America'

6. Testing Localized Output

Use Case: Unit tests for country name localization.

public function test_country_name_localization()
{
    Country::setLocale('fr');
    $this->assertEquals('France', Country::name('FR'));

    Country::setLocale('de');
    $this->assertEquals('Frankreich', Country::name('FR'));
}

Advanced Patterns

Custom Data Sources

Override the default data path in config/native-country-names.php:

'data_path' => base_path('custom/countries.json'),

Example custom/countries.json:

{
  "US": {
    "en": "United States of America",
    "custom": "USA (Custom)"
  }
}

Caching Strategy

Enable caching in config/native-country-names.php:

'cache_enabled' => true,

Cache Tags: Use Cache::tags(['native_countries']) to invalidate when data updates.

Event-Driven Updates

Listen for locale changes to update country names dynamically:

use LaravelLang\NativeCountryNames\Events\LocaleChanged;

LocaleChanged::listen(function ($locale) {
    Country::setLocale($locale);
});

Gotchas and Tips

Pitfalls

  1. Locale Mismatches:

    • Issue: Country::name('US') returns English names even if the app locale is fr.
    • Fix: Explicitly set the locale:
      Country::setLocale('fr');
      Country::name('US'); // 'États-Unis'
      
    • Tip: Use middleware to set the locale from user preferences:
      public function handle(Request $request, Closure $next)
      {
          app()->setLocale($request->user()->preferred_locale ?? 'en');
          return $next($request);
      }
      
  2. Data Updates:

    • Issue: The package updates data via GitHub Actions, but your local environment may lag.
    • Fix: Manually update the resources/data folder or use the update:data Artisan command (if available in future versions).
    • Tip: Monitor the release notes for data updates.
  3. Case Sensitivity:

    • Issue: Country codes are case-sensitive (e.g., US vs. us).
    • Fix: Normalize codes:
      $code = strtoupper($request->input('country'));
      
  4. Missing Locales:

    • Issue: A locale (e.g., zh-Hant for Traditional Chinese) is missing translations.
    • Fix: Contribute missing translations via GitHub Issues or extend the dataset locally.
  5. Performance with Large Lists:

    • Issue: Country::all() loads all 250+ countries into memory.
    • Fix: Lazy-load or paginate:
      $countries = collect(Country::all())->take(50);
      

Debugging Tips

  1. Verify Data Loading: Check if the JSON data is loaded correctly:

    dd(Country::all()->keys()); // Should return all country codes (e.g., ['US', 'FR', ...])
    
  2. Locale Debugging: Ensure the locale is set correctly:

    dd(app()->getLocale(), Country::getLocale());
    
  3. Cache Issues: Clear cache if names aren’t updating:

    php artisan cache:clear
    php artisan view:clear
    
  4. Data Validation: Validate country codes before use:

    if (!Country::exists('XX')) { // 'XX' = invalid code
        abort(400, 'Invalid country code');
    }
    

Extension Points

  1. Add Custom Country Names: Extend the dataset via a service provider:
    public function boot()
    {
        $customCountries = [
            'XX' => [
                'en' => 'Custom Land',
                'es' => 'Tierra Personalizada',
            ],
        ];
        Country::extend($customCountries);
    
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