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.
Install via Composer:
composer require laravel-lang/native-country-names
Publish Configuration (Optional):
php artisan vendor:publish --provider="LaravelLang\NativeCountryNames\ServiceProvider"
config/native-country-names.php for customization (e.g., default locale, caching).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)
Locale Switching:
Country::setLocale('es'); // Force Spanish locale
Country::name('US'); // 'Estados Unidos'
Fetch All Countries:
$countries = Country::all(); // Array of { code => name } pairs
LaravelLang\NativeCountryNames\Facades\Country
name(string $code, ?string $locale = null), all(), setLocale(string $locale).config/native-country-names.php
default_locale, cache_enabled, or data_path.resources/data/countries.json
{
"US": {
"en": "United States",
"fr": "États-Unis",
"es": "Estados Unidos",
...
}
}
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());
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;
});
});
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}.");
},
],
]);
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');
}
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'
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'));
}
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)"
}
}
Enable caching in config/native-country-names.php:
'cache_enabled' => true,
Cache Tags: Use Cache::tags(['native_countries']) to invalidate when data updates.
Listen for locale changes to update country names dynamically:
use LaravelLang\NativeCountryNames\Events\LocaleChanged;
LocaleChanged::listen(function ($locale) {
Country::setLocale($locale);
});
Locale Mismatches:
Country::name('US') returns English names even if the app locale is fr.Country::setLocale('fr');
Country::name('US'); // 'États-Unis'
public function handle(Request $request, Closure $next)
{
app()->setLocale($request->user()->preferred_locale ?? 'en');
return $next($request);
}
Data Updates:
resources/data folder or use the update:data Artisan command (if available in future versions).Case Sensitivity:
US vs. us).$code = strtoupper($request->input('country'));
Missing Locales:
zh-Hant for Traditional Chinese) is missing translations.Performance with Large Lists:
Country::all() loads all 250+ countries into memory.$countries = collect(Country::all())->take(50);
Verify Data Loading: Check if the JSON data is loaded correctly:
dd(Country::all()->keys()); // Should return all country codes (e.g., ['US', 'FR', ...])
Locale Debugging: Ensure the locale is set correctly:
dd(app()->getLocale(), Country::getLocale());
Cache Issues: Clear cache if names aren’t updating:
php artisan cache:clear
php artisan view:clear
Data Validation: Validate country codes before use:
if (!Country::exists('XX')) { // 'XX' = invalid code
abort(400, 'Invalid country code');
}
public function boot()
{
$customCountries = [
'XX' => [
'en' => 'Custom Land',
'es' => 'Tierra Personalizada',
],
];
Country::extend($customCountries);
How can I help you explore Laravel packages today?