NepalData
NepalData is a PHP library for looking up Nepal’s provinces, districts, and local levels. It runs in standalone PHP and integrates with Laravel through package discovery, a facade, and dependency injection.
| Included in each language | Records |
|---|---|
| Provinces | 7 |
| Districts | 77 |
| Metropolitan cities | 6 |
| Sub-metropolitan cities | 9 |
| Municipalities | 259 |
| Rural municipalities | 447 |
| Total local levels | 721 |
The data is bundled in English and Nepali. Once installed, NepalData needs no network requests, database, migrations, or package configuration. Use it to populate address forms, list local levels for a selected district, check relationships, or supply localized names to a user interface.
The typed API exposes read-only records and chainable queries. For example, this gets the names of rural municipalities in Kaski:
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\NepalData;
$data = new NepalData();
$names = $data->localLevels()
->whereDistrict(District::KASKI)
->ruralMunicipalities()
->orderByName()
->names();
This guide covers v2.0.0 of kodefarmers/nepaldata. Start with installation and the quick start, or jump directly to the public API. If you’re replacing a v1 installation, see the upgrade guide for how to preserve existing array responses.
The bundled records are a snapshot, and package IDs are not official government codes. Read Data Sources and Limitations before using the package where official completeness or current administrative boundaries matter.
Installation and Compatibility
NepalData v2 requires PHP 7.4 through 8.6 and the JSON extension. Use Composer 2. Laravel is optional, and Composer does not install Testbench or PHPUnit when you require NepalData in your own project.
Install a published release
From the root of your Composer project:
composer require "kodefarmers/nepaldata:^2.0"
In a new standalone project without a composer.json, initialize it first with composer init or let composer require create it. In Laravel, install into the application as usual. The provider is discovered automatically unless you have opted out; see Using NepalData in Laravel.
If Composer cannot find a published 2.x release, check Packagist or the release list. The v1 package has a different API.
Try a local source checkout
To use the v2 implementation before a tag is available, point a separate Composer project at a local checkout that contains the v2 code. Substitute the checkout’s actual path:
composer config repositories.nepaldata path "/path/to/nepaldata"
composer require "kodefarmers/nepaldata:@dev"
After the release is available, remove that repository override and require the stable version:
composer config --unset repositories.nepaldata
composer require "kodefarmers/nepaldata:^2.0"
Verified PHP and Laravel combinations
Each listed integration entry is Laravel / Orchestra Testbench / PHPUnit by major version. The latter two describe the package’s test environment, not additional packages for your application to install.
| PHP | Standalone PHP | Verified Laravel integrations |
|---|---|---|
| 7.4 | Yes | 8 / 6 / 9 |
| 8.0 | Yes | 8 / 6 / 9; 9 / 7 / 9 |
| 8.1 | Yes | 8 / 6 / 9; 9 / 7 / 9; 10 / 8 / 10 |
| 8.2 | Yes | 9 / 7 / 9; 10 / 8 / 10; 11 / 9 / 11; 12 / 10 / 11 |
| 8.3 | Yes | 10 / 8 / 10; 11 / 9 / 11; 12 / 10 / 12; 13 / 11 / 12 |
| 8.4 | Yes | 11 / 9 / 11; 12 / 10 / 12; 13 / 11 / 12 |
| 8.5 | Yes | 12 / 10 / 12; 13 / 11 / 12 |
| 8.6 | Yes | 13 / 11 / 12 |
These checks use installable patch releases of the listed major versions. Laravel 9 on PHP 8.0 requires PHP 8.0.2 or later. Laravel 12 on PHP 8.6 passed its assertions but emitted an upstream container deprecation and is outside the verified matrix. The other unlisted pairs are unverified.
The Laravel 8 through 11 CI jobs allow specific dependency versions that Composer would otherwise block because of security advisories. These exceptions apply only to the test jobs; consumer projects keep their own Composer security policy.
Quick Start
The standalone entry point is KodeFarmers\NepalData\NepalData. Create one instance, choose a dataset and language, then retrieve the records you need. In Laravel, the same service can be injected, or you can call the facade.
Run your first lookup
After installing NepalData, save this as nepaldata-example.php next to your project’s vendor/ directory:
<?php
declare(strict_types=1);
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\Entities\Province;
use KodeFarmers\NepalData\Language;
use KodeFarmers\NepalData\NepalData;
require __DIR__ . '/vendor/autoload.php';
$data = new NepalData();
$karnali = $data->provinces()->findOrFail(Province::KARNALI);
echo $karnali->name(), ': ', $karnali->districts()->count(), ' districts', PHP_EOL;
$kaski = $data->districts(Language::NEPALI)->findOrFail(District::KASKI);
echo $kaski->name(), ' -> ', $kaski->province()->name(), PHP_EOL;
$provinceNames = $data->provinces(Language::NEPALI)->orderByName()->names();
echo implode(', ', $provinceNames), PHP_EOL;
php nepaldata-example.php
The first two lines are Karnali: 10 districts and कास्की -> गण्डकी. The last line lists the seven province names from the Nepali snapshot. orderByName() uses bytewise UTF-8 order after ASCII case folding; it does not implement Nepali collation.
Choose the result you want
From that same $data instance:
use KodeFarmers\NepalData\Entities\District;
$query = $data->localLevels()->whereDistrict(District::KASKI)->ruralMunicipalities();
$records = $query->get(); // list<LocalLevel>
$names = $query->names(); // list<string>, in query order
$ids = $query->ids(); // list<int>, in query order
$rows = $query->toArray(); // scalar arrays, handy for JSON and form options
$count = $query->count(); // number of matching records
all() and get() return the same result for a given query. For one record, use find() to handle an absent ID with null, or findOrFail() if absence should raise an exception. first() returns the first match in the current order, or null when nothing matches.
Next: filter and search the catalogs, navigate relationships, or look up a named constant.
Using NepalData in Laravel
After installation, Laravel’s package discovery reads Composer’s metadata and registers KodeFarmers\NepalData\NepalDataServiceProvider. The provider binds the core service as a container singleton: facade calls and dependency injection resolve the same instance. Queries return independent filtered selections, so reusing this service does not carry a previous filter into a new call.
No config publishing, application migrations, or package-specific environment variables are required.
Use the facade
Import the facade from KodeFarmers\NepalData\Facades, not the standalone class of the same short name. A local alias keeps the distinction clear:
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\Facades\NepalData as Nepal;
use KodeFarmers\NepalData\Language;
$kaski = Nepal::districts(Language::NEPALI)->findOrFail(District::KASKI);
$ruralNames = $kaski->localLevels()->ruralMunicipalities()->names();
The facade exposes provinces(), districts(), localLevels(), and raw() with the same behavior as the core API. Its PHPDoc supplies the concrete query return types for editor and static-analysis tooling. The package does not register a global facade alias; use the explicit import.
Inject the core service
Type-hint KodeFarmers\NepalData\NepalData in a controller, service, or route. For example, add this to routes/web.php:
use Illuminate\Support\Facades\Route;
use KodeFarmers\NepalData\NepalData;
Route::get('/nepal/provinces', static fn (NepalData $data): array => $data->provinces()->toArray());
A request to /nepal/provinces returns the scalar province rows as JSON. The route is part of your application; NepalData itself registers no routes. To resolve the same instance explicitly in Laravel, use app(\KodeFarmers\NepalData\NepalData::class).
Use Laravel collections
use KodeFarmers\NepalData\Entities\Province;
use KodeFarmers\NepalData\Facades\NepalData as Nepal;
$query = Nepal::districts()->whereProvince(Province::GANDAKI)->orderByName();
$records = collect($query->get()); // Collection of District objects
$rows = collect($query->toArray()); // Collection of arrays
$options = $rows->pluck('name', 'id')->all(); // Names keyed by package district ID
Use get() when you need methods such as province() on the objects. Use toArray() when applying collection operations to scalar fields such as province_id. If you only need names, $query->names() is enough and does not require a collection.
If automatic discovery is disabled
Append \KodeFarmers\NepalData\NepalDataServiceProvider::class to the application’s existing provider list. The default location is bootstrap/providers.php in Laravel 11 or later, or the providers list in config/app.php in Laravel 8 through 10. Keep the rest of the provider list intact.
For standalone PHP, instantiate the core class directly as shown in the quick start. The facade needs a bootstrapped Laravel application.
Queries and Filters
The examples in this chapter use $data, the core instance from the quick start. Start with provinces(), districts(), or localLevels(). Each entry point returns a query, so you can add filters before asking for records, names, IDs, or a count.
Select by ID or relationship
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\Entities\Province;
$provinceNames = $data->provinces()->whereId(Province::GANDAKI, Province::KARNALI)->names();
$districtNames = $data->districts()
->whereProvince(Province::GANDAKI, Province::KARNALI)
->whereId(District::KASKI, District::KATHMANDU, District::HUMLA)
->names();
Here $districtNames is ['Kaski', 'Humla']. One filter call matches any value you pass. Chaining filters requires all those conditions to match. Kathmandu is excluded because it is in Bagmati. Repeating an ID does not duplicate the result. An unknown positive ID adds no matches and does not affect the other supplied IDs.
whereProvince() works on district and local level queries. whereDistrict() works on local level queries. A province or district record can also start the corresponding query.
Filter local level classifications
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\LocalLevelType;
$selection = $data->localLevels()->whereDistrict(District::KASKI, District::HUMLA);
$ruralNames = $selection->ruralMunicipalities()->orderByName()->names();
$urbanNames = $selection->municipalities()->orderByName()->names();
$ordinaryMunicipalities = $selection->whereType(LocalLevelType::MUNICIPALITY)->get();
municipalities() includes metropolitan cities, sub-metropolitan cities, and municipalities. Use whereType(LocalLevelType::MUNICIPALITY) for the ordinary municipality classification by itself. Pass more than one classification to whereType() when you want a particular combination. The accepted keys and the original abbreviations are listed in the API reference.
Each filter and orderByName() returns a new query. In the example, the rural and urban filters do not alter $selection or each other. Reuse the same base query for counts, option lists, or alternative filters.
Search and look up names
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\Language;
$kaski = $data->districts()->findByName('kaski'); // exact match, ignoring ASCII case
$nepaliMatches = $data->localLevels(Language::NEPALI)->search('फुङ')->names();
$allMadiRecords = $data->localLevels()->whereName('Madi')->get();
$madiInChitwan = $data->localLevels()
->whereDistrict(District::CHITWAN)
->findByName('Madi');
search()matches a substring in the current language.whereName()keeps every exact match, including repeated names in different districts.findByName()returns the only exact match ornull; it throwsDomainExceptionwhen there is more than one. Narrow the query first, as in the Chitwan example.
Both exact and substring matching ignore ASCII letter case. Spacing, punctuation, and non-ASCII text are compared as written. For example, the English record Taplejung(Phungling) can be found with search('phungling'); the Nepali query needs Nepali text. Search does not translate, transliterate, or normalize Unicode.
Use a custom filter
Pass a predicate that accepts the query’s record type and returns a boolean:
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\Entities\LocalLevel;
$selected = $data->localLevels()
->whereDistrict(District::KASKI)
->filter(static fn (LocalLevel $level): bool => in_array($level->name(), ['Annapurna', 'Pokhara'], true))
->orderByName()
->names();
The predicate runs only on the current selection. Exceptions from the predicate reach the caller; the original query remains unchanged.
Queries keep nested source order by default. orderByName() sorts ascending with ASCII case folding and bytewise UTF-8 comparison; ties use ascending ID. Further filters preserve the resulting order.
Handle missing records
find() and findOrFail() respect all current filters. find() returns null for an absent positive ID. findOrFail() raises OutOfBoundsException for the same miss. Invalid inputs, such as ID zero, an unsupported language or classification, or a blank search term, raise InvalidArgumentException instead. See Errors and Empty Results for the full contract.
Relationships and Output
Each local level belongs to a district, and each district belongs to a province in the bundled hierarchy:
Province
-> District
-> LocalLevel
Going from a parent to its children returns a query you can filter further. Going from a record to its parent returns that record directly. The parent’s language matches the record you started from.
Traverse the hierarchy
The examples below use $data from the quick start:
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\Entities\Province;
use KodeFarmers\NepalData\Language;
$gandaki = $data->provinces(Language::NEPALI)->findOrFail(Province::GANDAKI);
$districts = $gandaki->districts()->get();
$ruralLevels = $gandaki->localLevels()->ruralMunicipalities()->get();
$kaski = $gandaki->districts()->findOrFail(District::KASKI);
$provinceName = $kaski->province()->name(); // गण्डकी
$provinceId = $kaski->provinceId(); // Province::GANDAKI
$localLevel = $kaski->localLevels()->findByName('पोखरा');
if ($localLevel !== null) {
$district = $localLevel->district(); // कास्की
$province = $localLevel->province(); // गण्डकी
}
Use provinceId() or districtId() when you only need the integer parent ID. They expose the same values as province()->id() or district()->id(), respectively.
Prepare data for a form
get() and all() return zero-indexed PHP arrays of read-only objects. Use toArray() for scalar rows that work with helpers such as array_column():
use KodeFarmers\NepalData\Entities\Province;
$query = $data->districts()->whereProvince(Province::GANDAKI)->orderByName();
$options = array_column($query->toArray(), 'name', 'id'); // Names keyed by district ID
For a dependent select, take the validated province ID from the first field, filter districts with whereProvince(), and then filter local levels with whereDistrict() after the user chooses a district. Use the same language across all three lists. See Troubleshooting for an example of validating incoming IDs.
Serialize records and queries
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\Language;
$district = $data->districts(Language::NEPALI)->findOrFail(District::KASKI);
$row = $district->toArray();
$json = json_encode($district->localLevels(), JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
With json_encode(), a record produces one JSON object and a query produces a JSON array of objects, or [] if empty. Both implement JsonSerializable, and jsonSerialize() returns the same PHP array as toArray(). A list returned by get() can also be JSON-encoded because each item is serializable. JSON_UNESCAPED_UNICODE makes Nepali text readable in the output; JSON_THROW_ON_ERROR reports encoding errors as exceptions.
| Entity | Fields in toArray() and JSON |
|---|---|
Province | id, name, language |
District | id, name, language, province_id |
LocalLevel | id, name, language, province_id, district_id, type, type_label |
IDs are integers; the other fields are strings. Parent records and child queries are not included automatically. If your client needs a nested hierarchy or just a handful of fields, assemble that response explicitly from the records and relationships you need. Use original arrays if the client relies on the exact v1 shape instead.
Changing an array returned by toArray() or raw() does not change the package data. Replacing items in a list returned by get() likewise does not affect the query or later calls.
Languages and Identifiers
The three typed entry points and each original array view accept an optional language code:
| Constant | Value | Meaning |
|---|---|---|
Language::ENGLISH | 'en' | English, the default |
Language::NEPALI | 'ne' | Nepali, written in Devanagari |
Pass Language::NEPALI when starting a query; a relationship reached from one of its records stays in Nepali. The language also determines the values returned by name() and, for local levels, typeLabel(). type() uses a language-independent key from LocalLevelType.
use KodeFarmers\NepalData\Entities\Province;
use KodeFarmers\NepalData\Language;
$english = $data->provinces(Language::ENGLISH)->findOrFail(Province::MADHESH);
$nepali = $data->provinces(Language::NEPALI)->findOrFail(Province::MADHESH);
echo $english->name(), ' / ', $nepali->name(), PHP_EOL; // Madhesh / मधेश
'english', 'nepali', 'devanagari', and 'np' are not accepted v2 language codes. An unsupported value raises InvalidArgumentException. Laravel’s current application locale does not set the package language automatically.
Stable province and district IDs
Use Province::KARNALI, District::KASKI, and the other named constants for province and district lookups. These are integer package IDs, shared across English and Nepali. Use a province constant for whereProvince() and a district constant for whereDistrict().
IDs are scoped to their dataset. A province ID and a district ID can have the same integer value and refer to different places. Store the dataset alongside an ID if your application handles multiple record types. The package exposes no government administrative codes.
Prefer constants over comparisons on display names. The province in the example above is Madhesh in the typed English catalog but Madesh in some original arrays. The constant identifies the typed record without requiring the caller to account for different spellings. Constants can also be used to retrieve localized labels for the same province or district side by side.
Snapshot-specific local level IDs
Local level IDs are one-based positions in the selected language’s nested source snapshot. They are unique within that language’s local level catalog and retained when you filter or sort, but they are not durable identifiers across snapshots. English and Nepali local level IDs have no supported mapping.
Use a local level ID with the language in which you obtained it. Do not assume that fetching the same integer in the other language retrieves a translation. If you need a durable identifier for local levels in your own system, maintain your own key alongside the source and language you recorded. A name alone is not necessarily unique.
When exact spelling matters, search within the intended language and narrow to the known district. See Queries and Filters.
Original Arrays
Use raw() when a v1 consumer needs the original payload, including spellings, keys, category labels, and order. The accessor is available on the standalone service and the Laravel facade. Each view accepts the same optional language parameter as the typed API.
The five views
Method on RawData | Shape | Original file |
|---|---|---|
all() | Province name -> district name -> classification label -> list of local level names | src/Datas/allData.php |
provinces() | List of province names | src/Datas/provinces.php |
districts() | List of district names | src/Datas/districts.php |
provincesWithDistricts() | Province name -> list of district names | src/Datas/provincesWithDistricts.php |
districtsWithLocalBodies() | District name -> classification label -> list of local level names | src/Datas/districtsWithLocalBodies.php |
The leaf values are plain PHP strings. Empty groups remain empty arrays. The raw methods do not return records or query objects, do not attach package IDs, and do not combine the two languages.
Read a branch of the hierarchy
use KodeFarmers\NepalData\Language;
$raw = $data->raw();
$englishHierarchy = $raw->all();
$ruralNames = $englishHierarchy['Koshi']['Taplejung']['Ga.Pa.'];
$nepaliDistrictNames = $raw->districts(Language::NEPALI);
$nepaliGroups = $raw->districtsWithLocalBodies(Language::NEPALI)['ताप्लेजुङ'];
An English Ga.Pa. group is the corresponding गा.पा. classification in the Nepali view. Refer to the classification table for all four labels. When accessing nested arrays by an input value, check the key is present (for example, with ?? []) or use the typed queries’ parent filters.
These views preserve differences in the original source. For instance, raw()->provinces() uses Madesh while raw()->all() uses Madhesh as the province key. Do not assume you can use an arbitrary value from one view as a key in another. See Data Sources and Limitations for a comparison, or Upgrading from v1 for migration examples.
Data Sources and Limitations
NepalData v2 ships the five PHP data files from the v1 repository, byte-for-byte as found in the source checkout for the rewrite. The original repository does not identify a dated authoritative publication or a separate data license. Treat these files as a bundled snapshot of the package’s source; they do not establish the completeness or accuracy of the current official registry.
The snapshot does not provide official administrative codes, coordinates, boundaries, ward records, or an authoritative bilingual mapping for local levels. The 721 local levels in each language are the records in this package, not a claim about the current official total. Some districts are particularly sparse: Dhanusa, for example, has one local level in the bundled hierarchy.
Which file does the typed API use?
The typed catalog follows allData.php, which provides the province, district, classification, and local level hierarchy for each language. Using one hierarchy keeps parent-child relationships consistent and avoids joining on names that vary among the other files. The remaining views are accessible through raw().
The core loads the raw views on demand and keeps an in-memory catalog for each language it uses. Within a catalog, dataset indexes are built when needed; record IDs make direct lookups possible without re-reading the files. ID constants map to the exact source names for provinces and districts. For local levels, the index follows the source order of the selected language. Filters and sorting derive separate read-only selections. None of this uses a database, persistent cache, or network service.
Differences to account for
| Area | What differs |
|---|---|
| English province names | provinces() and provincesWithDistricts() in raw() say Madesh; raw()->all() and the typed catalog say Madhesh. |
| English district names | The flat district list and province-to-district map say Kavrepalanchowk and Tehrathum; the hierarchy and district-to-local-level map say Kavrepalanchok and Terhathum. |
| Nepali district count | The original flat list contains 79 entries. The nested hierarchy and province-to-district map each contain 77. |
| Local level names | Names are not necessarily unique, even within one language. For example, Madi occurs in four English district entries. The typed catalog preserves each occurrence with its source classification and parent. |
The Nepali flat-list-only district names are वैतडी, कन्चनपुर, काभ्रेपालाञ्चोक, नवलपरासी ( बर्दघाट सुस्ता पूर्व ), नवलपरासी ( बर्दघाट सुस्ता पश्चिम ), रुकुम, रुकुम ( पूर्वी भाग ), रुकुम ( पश्चिम भाग), and संखुवासभा. Names present in the nested hierarchy but absent from the flat list are बैतडी, कञ्चनपुर, काभ्रेपलान्चोक, नवलपुर, पूर्वी रुकुम, पश्चिम रुकुम, and सङ्खुवासभा.
The raw district-to-local-level map matches the nested hierarchy when flattened by district in either language. The English and Nepali flat lists are not a reliable record-by-record translation table. Use the stable province and district constants for bilingual lookups of those two entity types.
For a correction, follow Testing and Contributing. The DATA.md file in the v2 package source also records these observations.
Public API
This chapter lists the consumer API. The namespace prefix is KodeFarmers\NepalData. Import record classes from Entities and query classes from Queries under that namespace. Obtain records and queries from the core, the Laravel facade, or a relationship; their constructors and the internal catalog are not consumer APIs.
Entry points
Create the standalone service with new NepalData(). In Laravel, inject KodeFarmers\NepalData\NepalData or import the facade KodeFarmers\NepalData\Facades\NepalData and call the same entry points statically.
| Method | Return type |
|---|---|
provinces(string $language = Language::ENGLISH) | ProvinceQuery |
districts(string $language = Language::ENGLISH) | DistrictQuery |
localLevels(string $language = Language::ENGLISH) | LocalLevelQuery |
raw() | RawData |
Language::ENGLISH is 'en', and Language::NEPALI is 'ne'. A language applies to the entire query and to relationships reached from its results. See Languages and Identifiers.
Methods shared by all queries
T denotes the specific entity: Province, District, or LocalLevel.
| Method | Result |
|---|---|
all(), get() | list<T>: all current matches as a zero-indexed PHP array. |
first() | T for the first current match, or null. |
find(int $id) | The matching T in the current query, or null. |
findOrFail(int $id) | The matching T, or OutOfBoundsException if the ID has no match. |
whereId(int $id, int ...$moreIds) | A new query matching any supplied ID in the current selection. |
whereName(string $name) | A new query keeping every exact name match. |
findByName(string $name) | A single exact match as T, null if absent, or DomainException if ambiguous. |
search(string $term) | A new query keeping names that contain the term. |
filter(callable $predicate) | A new query keeping records accepted by a predicate with the signature callable(T): bool. |
orderByName() | A new query ordered by name, with ascending ID breaking ties. |
count() or count($query) | The number of matches. Queries implement Countable. |
ids() | list<int> of matching IDs in query order. |
names() | list<string> of matching names in query order, including repeated names. |
toArray() | A list of scalar row arrays in query order. |
jsonSerialize() | The same row list as toArray(). json_encode($query) encodes it as JSON. |
Use get() or all() before iterating with foreach. Queries themselves provide counting and JSON serialization; they are not iterators. See Queries and Filters for ordering and predicate examples.
Administrative filters
| Method | Available on | Effect |
|---|---|---|
whereProvince(int $provinceId, int ...$moreProvinceIds) | DistrictQuery, LocalLevelQuery | Keeps records within any supplied province ID. |
whereDistrict(int $districtId, int ...$moreDistrictIds) | LocalLevelQuery | Keeps records within any supplied district ID. |
whereType(string $type, string ...$moreTypes) | LocalLevelQuery | Keeps records matching any supplied LocalLevelType key. |
municipalities() | LocalLevelQuery | Keeps metropolitan cities, sub-metropolitan cities, and municipalities. |
ruralMunicipalities() | LocalLevelQuery | Keeps only rural municipalities. |
Each returns the same concrete type of query with the filter applied. Alternatives within a call match any supplied value; separate calls narrow the previous selection.
Records and relationships
Every record has id(): int, name(): string, language(): string, toArray(): array, and jsonSerialize(): array. Records are read-only. Names preserve their source spelling. Array and JSON output include only scalar fields.
| Record | Additional methods | Additional fields in scalar output |
|---|---|---|
Province | districts(): DistrictQuery, localLevels(): LocalLevelQuery | - |
District | province(): Province, provinceId(): int, localLevels(): LocalLevelQuery | province_id |
LocalLevel | district(): District, districtId(): int, province(): Province, provinceId(): int, type(): string, typeLabel(): string | province_id, district_id, type, type_label |
The common fields are id, name, and language. province_id and district_id are integer package IDs. The three record classes live in KodeFarmers\NepalData\Entities. Named IDs for the first two are listed in Province and District Constants. For examples, see Relationships and Output.
LocalLevelType
Use the constants on KodeFarmers\NepalData\LocalLevelType with whereType(). A record’s type() returns the key; typeLabel() returns the original abbreviation.
| Constant | Classification key | English label | Nepali label |
|---|---|---|---|
METROPOLITAN_CITY | metropolitan_city | Ma.Na.Pa. | म.न.पा. |
SUB_METROPOLITAN_CITY | sub_metropolitan_city | Upa.Ma. | उप-म. |
MUNICIPALITY | municipality | Na.Pa. | न.पा. |
RURAL_MUNICIPALITY | rural_municipality | Ga.Pa. | गा.पा. |
These source abbreviations are labels, not accepted arguments to whereType().
RawData
raw() returns KodeFarmers\NepalData\RawData. Its five methods are all(), provinces(), districts(), provincesWithDistricts(), and districtsWithLocalBodies(). Each accepts string $language = Language::ENGLISH and returns the original PHP array for that view. See Original Arrays for each shape and source file.
Errors and empty results
| Situation | Result |
|---|---|
find(), findByName(), or first() has no match | null |
A valid positive ID has no match for findOrFail() | OutOfBoundsException |
Several records match findByName() | DomainException |
| No records remain after filtering | [] from list/array methods, 0 from count(), null from first() |
| ID less than 1, unsupported language or classification, or a blank or malformed UTF-8 term | InvalidArgumentException |
| Wrong PHP argument type in a strict caller | TypeError |
| Writing properties on a record or query | LogicException |
An unknown positive ID is a valid lookup value that matches no record. It does not cancel other matches in a filter that accepts multiple IDs. A record filtered out of the current query is treated the same as an absent record. User-supplied predicates can also throw their own exceptions, which the package does not intercept.
Province and District Constants
The tables list every named province and district in the typed catalog. The English and Nepali columns show exact names from that catalog. Use the constants rather than hard-coded integers in your application:
use KodeFarmers\NepalData\Entities\District;
use KodeFarmers\NepalData\Entities\Province;
$kaski = $data->districts()->whereProvince(Province::GANDAKI)->findOrFail(District::KASKI);
These are stable NepalData IDs within their respective datasets. They are not official administrative codes. Local levels do not have this kind of named ID; see Languages and Identifiers.
Provinces
| Constant | ID | English | Nepali |
|---|---|---|---|
Province::KOSHI | 1 | Koshi | कोशी |
Province::MADHESH | 2 | Madhesh | मधेश |
Province::BAGMATI | 3 | Bagmati | बागमती |
Province::GANDAKI | 4 | Gandaki | गण्डकी |
Province::LUMBINI | 5 | Lumbini | लुम्बिनी |
Province::KARNALI | 6 | Karnali | कर्णाली |
Province::SUDURPASHCHIM | 7 | Sudurpashchim | सुदूरपश्चिम |
Districts by province
Some named constants follow the original flat lists: District::TEHRATHUM returns the English name Terhathum in the typed catalog, and District::KAVREPALANCHOWK returns Kavrepalanchok. See Data Sources and Limitations.
Koshi
| Constant | ID | English | Nepali |
|---|---|---|---|
District::TAPLEJUNG | 1 | Taplejung | ताप्लेजुङ |
District::PANCHTHAR | 2 | Panchthar | पाँचथर |
District::ILAM | 3 | Ilam | इलाम |
District::JHAPA | 4 | Jhapa | झापा |
District::MORANG | 5 | Morang | मोरङ |
District::SUNSARI | 6 | Sunsari | सुनसरी |
District::DHANKUTA | 7 | Dhankuta | धनकुटा |
District::TEHRATHUM | 8 | Terhathum | तेह्रथुम |
District::SANKHUWASABHA | 9 | Sankhuwasabha | सङ्खुवासभा |
District::BHOJPUR | 10 | Bhojpur | भोजपुर |
District::SOLUKHUMBU | 11 | Solukhumbu | सोलुखुम्बु |
District::OKHALDHUNGA | 12 | Okhaldhunga | ओखलढुङ्गा |
District::KHOTANG | 13 | Khotang | खोटाङ |
District::UDAYAPUR | 14 | Udayapur | उदयपुर |
Madhesh
| Constant | ID | English | Nepali |
|---|---|---|---|
District::SAPTARI | 15 | Saptari | सप्तरी |
District::SIRAHA | 16 | Siraha | सिराहा |
District::DHANUSA | 17 | Dhanusa | धनुषा |
District::MAHOTTARI | 18 | Mahottari | महोत्तरी |
District::SARLAHI | 19 | Sarlahi | सर्लाही |
District::BARA | 20 | Bara | बारा |
District::PARSA | 21 | Parsa | पर्सा |
District::RAUTAHAT | 22 | Rautahat | रौतहट |
Bagmati
| Constant | ID | English | Nepali |
|---|---|---|---|
District::SINDHULI | 23 | Sindhuli | सिन्धुली |
District::RAMECHHAP | 24 | Ramechhap | रामेछाप |
District::DOLAKHA | 25 | Dolakha | दोलखा |
District::SINDHUPALCHOK | 26 | Sindhupalchok | सिन्धुपाल्चोक |
District::KAVREPALANCHOWK | 27 | Kavrepalanchok | काभ्रेपलान्चोक |
District::LALITPUR | 28 | Lalitpur | ललितपुर |
District::BHAKTAPUR | 29 | Bhaktapur | भक्तपुर |
District::KATHMANDU | 30 | Kathmandu | काठमाडौँ |
District::NUWAKOT | 31 | Nuwakot | नुवाकोट |
District::RASUWA | 32 | Rasuwa | रसुवा |
District::DHADING | 33 | Dhading | धादिङ |
District::MAKWANPUR | 34 | Makwanpur | मकवानपुर |
District::CHITWAN | 35 | Chitwan | चितवन |
Gandaki
| Constant | ID | English | Nepali |
|---|---|---|---|
District::GORKHA | 36 | Gorkha | गोरखा |
District::LAMJUNG | 37 | Lamjung | लमजुङ |
District::TANAHU | 38 | Tanahu | तनहुँ |
District::SYANGJA | 39 | Syangja | स्याङ्जा |
District::KASKI | 40 | Kaski | कास्की |
District::MANANG | 41 | Manang | मनाङ |
District::MUSTANG | 42 | Mustang | मुस्ताङ |
District::MYAGDI | 43 | Myagdi | म्याग्दी |
District::NAWALPUR | 44 | Nawalpur | नवलपुर |
District::PARBAT | 45 | Parbat | पर्वत |
District::BAGLUNG | 46 | Baglung | बाग्लुङ |
Lumbini
| Constant | ID | English | Nepali |
|---|---|---|---|
District::GULMI | 47 | Gulmi | गुल्मी |
District::PALPA | 48 | Palpa | पाल्पा |
District::PARASI | 49 | Parasi | नवलपरासी |
District::RUPANDEHI | 50 | Rupandehi | रुपन्देही |
District::KAPILVASTU | 51 | Kapilvastu | कपिलवस्तु |
District::ARGHAKHANCHI | 52 | Arghakhanchi | अर्घाखाँची |
District::PYUTHAN | 53 | Pyuthan | प्युठान |
District::ROLPA | 54 | Rolpa | रोल्पा |
District::EASTERN_RUKUM | 55 | Eastern Rukum | पूर्वी रुकुम |
District::BANKE | 56 | Banke | बाँके |
District::BARDIYA | 57 | Bardiya | बर्दिया |
District::DANG | 58 | Dang | दाङ |
Karnali
| Constant | ID | English | Nepali |
|---|---|---|---|
District::WESTERN_RUKUM | 59 | Western Rukum | पश्चिम रुकुम |
District::SALYAN | 60 | Salyan | सल्यान |
District::SURKHET | 61 | Surkhet | सुर्खेत |
District::DAILEKH | 62 | Dailekh | दैलेख |
District::JAJARKOT | 63 | Jajarkot | जाजरकोट |
District::DOLPA | 64 | Dolpa | डोल्पा |
District::JUMLA | 65 | Jumla | जुम्ला |
District::KALIKOT | 66 | Kalikot | कालिकोट |
District::MUGU | 67 | Mugu | मुगु |
District::HUMLA | 68 | Humla | हुम्ला |
Sudurpashchim
| Constant | ID | English | Nepali |
|---|---|---|---|
District::BAJURA | 69 | Bajura | बाजुरा |
District::BAJHANG | 70 | Bajhang | बझाङ |
District::ACHHAM | 71 | Achham | अछाम |
District::DOTI | 72 | Doti | डोटी |
District::KAILALI | 73 | Kailali | कैलाली |
District::KANCHANPUR | 74 | Kanchanpur | कञ्चनपुर |
District::DADELDHURA | 75 | Dadeldhura | डडेल्धुरा |
District::BAITADI | 76 | Baitadi | बैतडी |
District::DARCHULA | 77 | Darchula | दार्चुला |
Upgrading from v1
The Composer package remains kodefarmers/nepaldata, the PHP namespace remains KodeFarmers\NepalData, and the Laravel facade import is unchanged. Update your Composer constraint to ^2.0 and choose which callers should keep the original arrays and which should move to the typed API.
Preserve existing array responses
If a template, test fixture, stored payload, or downstream API client expects v1’s exact keys and values, start with raw(). In this table, NepalData:: refers to the Laravel facade. In standalone PHP, use $data->raw() on the core service.
| v1 call | v2 equivalent |
|---|---|
NepalData::all() or NepalData::getAllData() | NepalData::raw()->all() |
NepalData::all('nepali'), NepalData::all('devanagari'), or NepalData::getAllDataInDevanagari() | NepalData::raw()->all(Language::NEPALI) |
NepalData::provinces() | NepalData::raw()->provinces() |
NepalData::districts() | NepalData::raw()->districts() |
NepalData::with('districts')->provinces() | NepalData::raw()->provincesWithDistricts() |
NepalData::with('localbodies')->districts() | NepalData::raw()->districtsWithLocalBodies() |
Import KodeFarmers\NepalData\Language for the named language values. Omit the argument for English, or use Language::ENGLISH. Replace both old Nepali aliases with Language::NEPALI. The v2 API rejects unsupported codes instead of defaulting to English.
To reproduce with('localbodies')->only('administrations')->districts() in Nepali, flatten the group arrays within each district. The outer district keys are preserved:
use KodeFarmers\NepalData\Language;
$groupsByDistrict = $data->raw()->districtsWithLocalBodies(Language::NEPALI);
$namesByDistrict = array_map(
static fn (array $groups): array => array_merge(...array_values($groups)),
$groupsByDistrict
);
Omit the language argument for the English equivalent.
Adopt the typed API
provinces() and districts() now return query objects. Terminate a query with get() or all() for typed records, or toArray() for the new scalar row shape. localLevels() is now its own typed entry point. with() and only() are gone; query filters and relationships are explicit and produce independent selections.
use KodeFarmers\NepalData\Entities\Province;
$province = $data->provinces()->findOrFail(Province::KOSHI);
$districts = $province->districts()->get();
$ruralRows = $province->localLevels()->ruralMunicipalities()->toArray();
The typed API follows the nested source hierarchy, so names and ordering may differ from v1’s flat lists. Do not replace a legacy array call with a typed query’s toArray() if you need backward-compatible output: one preserves the old shape and the other exports v2 fields.
If Laravel code used app('NepalData'), change it to app(\KodeFarmers\NepalData\NepalData::class) or inject that class directly. The Laravel chapter shows both the facade and dependency injection. Use stable province and district constants for the typed API; local level IDs are only valid within the relevant language and data snapshot.
Troubleshooting
Composer cannot install ^2.0
Check the published versions, the PHP version used by Composer, and the JSON extension. php -v and php -m report your current CLI runtime. After installation, composer show kodefarmers/nepaldata reports the installed version and composer check-platform-reqs checks the actual PHP environment rather than a simulated config.platform value.
If the installed package is v1, its calls return a different shape. See Upgrading from v1. For testing unpublished v2 code in a separate Composer project, use the local source checkout instructions.
Laravel cannot resolve the facade
- If calling a method statically, import
KodeFarmers\NepalData\Facades\NepalData, notKodeFarmers\NepalData\NepalData. For dependency injection, type-hint the latter. - Check whether the application disables package discovery. If so, register the provider in the existing provider list. If discovery is enabled,
php artisan package:discoverrebuilds the package manifest. - The facade needs an initialized Laravel application. In a plain PHP script with only Composer’s autoloader, create
new \KodeFarmers\NepalData\NepalData()instead.
A lookup returns nothing or throws
Confirm the selected language, the type of record, and the filters that are already applied. For example, $data->districts()->whereProvince(Province::KARNALI)->find(District::KASKI) returns null because Kaski is in Gandaki. An absent positive ID is different from an invalid ID such as zero.
If findByName() throws DomainException, several selected records have the same name. Filter by district or province first, or use whereName($name)->get() to show all candidates. If a lookup misses a familiar spelling, check the returned source names or use search() with a substring in the selected language. The package does not translate, strip punctuation, or apply locale-aware collation.
findOrFail() throws PHP’s OutOfBoundsException; it is not an Eloquent lookup and does not automatically turn a missing record into an HTTP 404. In an application action, handle null from find() or map the exception to your own response as appropriate. The error table lists the remaining cases.
Validate input before querying
HTML form fields typically arrive as strings. Validate IDs and language codes before passing them to the package. This standalone example validates a positive integer and then checks that it is an actual province ID:
use KodeFarmers\NepalData\Entities\Province;
$submittedProvince = (string) Province::GANDAKI; // Replace with the submitted scalar value.
$provinceId = filter_var($submittedProvince, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
if ($provinceId === false) {
throw new InvalidArgumentException('Select a valid province ID.');
}
$province = $data->provinces()->find($provinceId);
if ($province === null) {
throw new OutOfBoundsException('The selected province does not exist.');
}
$districtOptions = array_column($province->districts()->toArray(), 'name', 'id');
If both a province and a district are submitted, validate the district ID by looking it up on $province->districts() so the relationship is checked too. In Laravel, use request validation for integer with min:1 and an allowlist of en,ne for a submitted language, then cast the validated ID to int before querying.
Output is empty or does not match v1
Iterate over $query->get() or $query->all() rather than the query object itself. toArray() and JSON output contain scalar fields, not loaded child records. For exact v1 nested arrays, use raw()->all() in the desired language. For original flat names, use the corresponding raw view rather than trying to reconstruct it from typed records.
Testing and Contributing
Work in a source checkout of the NepalData package repository. The distributed archive contains the package and its documentation; the test suite and development tools come from the source repository.
Run the package checks
Use PHP 8.4 and Composer 2 for the standard development workflow:
composer install
composer test
composer test:unit
composer test:integration
composer analyse
test:unit exercises the standalone queries, records, and data. test:integration uses Orchestra Testbench to check the service provider, facade, dependency injection, and package metadata. composer test runs both suites. PHPStan analyzes the runtime against PHP 7.4 at its maximum level.
For formatting, install Laravel Pint on the development runtime and run its check from the package root:
composer global require "laravel/pint:^1.32"
pint --test
If pint is not on PATH, find Composer’s global bin directory with composer global config bin-dir --absolute. Omit --test to apply formatting. The preserved raw files are excluded from formatting and static analysis.
With Xdebug installed, generate a coverage report with:
XDEBUG_MODE=coverage composer test -- --coverage-filter src --coverage-text
What CI verifies
The v2 package workflow at .github/workflows/ci.yml verifies standalone consumer installs throughout the supported PHP range, runs unit and Laravel tests on the listed combinations, and checks that Composer archives include the source without bundled vendor dependencies or local configuration files. A standalone smoke test uses the autoloader of a separate consumer project without Laravel or PHPUnit.
The integrity tests fingerprint all ten original views (five per language) and rebuild each typed hierarchy from relationships. They catch changes in keys, spelling, order, or parent-child associations. Keep those checks intact when changing query code.
Report a data correction
Open a package issue with the affected language, source file or raw view, and exact record. For a proposed correction, include a dated official or authoritative reference and note the other language or views that could be affected. The v2 modernization preserved the existing snapshot deliberately; do not replace its spellings or records in a code-only change.
For behavioral bugs, include a minimal example, installed package version, PHP version, and Laravel version if applicable.
Maintain the package and the guide
Keep package runtime syntax compatible with PHP 7.4, preserve stable province and district IDs, and cover observable behavior with tests. If an approved change alters a source spelling, update the exact-name mapping in src/Internal/AdministrativeNames.php without changing the existing ID, and update the integrity expectations only for the intended data change.
Update the affected guide chapters and the constants appendix when the package contract changes. Use mdbook build from the guide directory to regenerate the HTML, and mdbook serve --open to preview edits. The editable Markdown lives in src/; do not edit generated files in book/.
The v2 source checkout contains CHANGELOG.md and CONTRIBUTING.md. See the release list for published versions.
License
NepalData is released under the MIT License. The data notes explain the provenance of the bundled snapshot and the limits of the source attribution.
MIT License
Copyright (c) 2023 kodefarmers
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.