Get expert guidance in a few days with a Laravel code review

Multilingual Country List

petercoles/multilingual-country-list image

Multilingual Country List stats

Downloads
190.6K
Stars
120
Open Issues
1
Forks
32

View on GitHub →

Lookup Objects for ISO 3166 Country Names and Codes

Multilingual Country Lists for Laravel

Introduction

I've lost count of the number of times that I've carefully edited a list of 250 of so countries to create the data needed for a select field on a form - and that's just for one language. This thin Laravel wrapper around an industry-maintained list of country names in many, many languages, consigns that tedious task and ongoing maintenance of those lists to the trash bin of history.

The package provides easy access, through a simple API, to country names in an enormously large number of language and locale settings, together with their ISO-3166 alpha-2 two-letter country codes.

Data can be returned as a lookup array or an array of key-value pairs, where both the key and value labels can be set according to the needs of the software consuming them.

Installation

At the command line run

composer require petercoles/multilingual-country-list

If you're using Laravel 5.5 or later (and haven't disabled package discovery), you're done. Move on to the usage section below.

If you're using an older version of Laravel, then add the service provider to the providers entry in your config/app.php file

'providers' => [
// ...
PeterColes\Countries\CountriesServiceProvider::class,
// ...
],

An optional facade is also available and can be enabled by adding the following to the aliases array in your config/app.php file.

'Countries' => PeterColes\Countries\CountriesFacade::class,

Usage

Once installed the package exposes two API methods: lookup() and keyValue(), each of which returns a list of countries ordered by the country name in the language being used.

Lookup

The lookup method takes two optional parameters: $locale (default 'en') and $flip (default false) and returns a collection. This collection will be cast to a json object by Laravel if returned as a response, or can be cast to an array if needed with the toArray() method.

Locales can be expressed as a language code, e.g. 'fr', or a full locale code, e.g. zh_CN.

Lookup Examples

The default is English.

Countries::lookup();
 
// returns
 
{
"AF": "Afghanistan",
...
"ZW": "Zimbabwe"
}

The flip parameter facilitates reverse lookups, e.g. for typahead components that recognize values, but don't support keys, requiring the key to obtained later.

Countries::lookup('es', true);
 
// returns
 
{
"Afganistán": "AF",
...
"Zimbabue": "ZW"
}

Non-latin character sets are supported too, including locale settings

Countries::lookup('zh_CN');
 
// returns
 
{
"AL": "阿尔巴尼亚",
...
"HK": "中国香港特别行政区"
}

keyValue

The keyValue method takes three optional parameters: $locale (default 'en'), $key (default 'key') and $value (default 'value').

Key Value Examples

The default is still English.

Countries::keyValue();
 
// returns
 
[
{"key": "AF", "value": "Afghanistan"},
...
{"key": "ZW", "value": "Zimbabwe"}
]

If you need a key-value list with custom indices, then the $key and $value parameters can be used to redfine them. this might be the case, for example, if you're using a javascript component to generate a select field and that component has expectations as to the indices used in the data that it receoves.

Countries::keyValue('zh', 'label', 'text');
 
// returns
 
[
{"label": "AL", "text": "阿尔巴尼亚"},
...
{"label": "HK", "text": "中国香港特别行政区"}
]

Country Names

If you just want to get the name of a country for a particular locale, then passing the $isoCode and $locale (default 'en') to the countryName method will return the requested text.

Country Name Example

Countries::countryName('BE', 'fr')
 
// returns
 
'Belgique'

Tweaking

So, you've got a list of countries, but it doesn't quite meet your needs. Since the lookup and keyValue methods return Laravel collections, tweaking the results is super easy.

Filtering

The data from which these lists are drawn includes "Eurozone" and, despite some politicans wishes, that's not really a country. Let's remove it.

Countries::lookup()->reject(function($country, $key) {
return $key == 'EZ';
});

There are also some entries that may be considered parts of other countries. Without getting into the politics, let's also remove the Canary Islands (Spain) and Guadeloupe (France).

Countries::lookup()->reject(function($country, $key) {
return in_array($key, [ 'EZ', 'IC', 'GP' ]);
});

Modifying

Also, we know that the international code for the United Kingdom is "GB", but our payment gateway is expecteding "UK". So lets change that.

Countries::lookup()->mapWithKeys(function($country, $key) {
return $key == 'GB' ? [ 'UK' => $country ] : [ $key => $country ];
});

Adding

The number of recognized countries is growing, but not always as fast as changes on the ground, so, with no comment on the political rights and wrongs, let's add a new one.

Countries::lookup()->put('CT', 'Catalonia')->sort();

A few warnings here:

  • Do check that the code isn't being already.
  • Do remember to sort the list after making the addition.
  • Don't forget to keep checking the list so that you can remove your addition if it becomes official.

Issues

This package was developed to meet a specific need and then generalised for wider use. If you have a use case not currently met, or see something that appears to not be working correctly, please raise an issue at the github repo.

Contributions

Contributions are welcome, but will generally need tests. I recommend raising an issue first so that proposed changes or enhancements can be discussed before development starts.

License

This package is licensed under the MIT license.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.


Petercoles Multilingual Country List Related Articles

Laravel TOON: Reduce LLM Token Usage by 40-60% image

Laravel TOON: Reduce LLM Token Usage by 40-60%

Read article
Laravel Analytics Beyond Visits – Track Conversions, Revenue & More with SimpleStats image

Laravel Analytics Beyond Visits – Track Conversions, Revenue & More with SimpleStats

Read article
Use the New Fluent Helper to Work With Multi-dimensional Arrays in Laravel 11.2 image

Use the New Fluent Helper to Work With Multi-dimensional Arrays in Laravel 11.2

Read article
LangCountry is a Localization Package for Laravel image

LangCountry is a Localization Package for Laravel

Read article
Writing and debugging Eloquent queries with Tinkerwell image

Writing and debugging Eloquent queries with Tinkerwell

Read article
Lemon Squeezy for Laravel image

Lemon Squeezy for Laravel

Read article
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec