Search by

ozkanozcan / laravel-turkiye

ozkanozcan

Laravel 11-13 Turkish address data: provinces, districts, neighbourhoods and postal codes

Package info

github.com/ozkanozcan/laravel-turkiye

pkg:composer/ozkanozcan/laravel-turkiye

Statistics

Installs: 0

Dependents: 0

Suggesters: 1

Stars: 0

Open Issues: 0

v1.0.0 2026-12-02 11:31 UTC

This package is auto-updated.

Last update: 2026-12-02 11:38:55 UTC


README

Tests Latest Version on Packagist PHP Version Laravel Version License: MIT

Turkish administrative address data for Laravel 11, 12, and 13: provinces (il), districts (ilçe), neighbourhoods (mahalle) and postal codes (posta kodu).

A community package, not an official Laravel package.

This is the PHP sibling of the Rust crate laravel-turkiye (crates.io), which serves the same data to Laravel Rust. Both share the same embedded data files and the same behaviour.

  • The 81 provinces (plate code, name, slug, region, area codes) and 973 districts are built into the package. No database is needed to use them.
  • Lookups ignore Turkish case and accents: "istanbul", "İSTANBUL" and "Istanbul" all find İstanbul.
  • Turkish text helpers (İ/ı rules, title case, ASCII slugs, alphabetical order).
  • Validation rules: postal code (five digits, first two digits = plate code), province exists, district belongs to province.
  • Eloquent models, migrations and php artisan turkiye:seed for the embedded data.
  • php artisan turkiye:install imports neighbourhoods and postal codes from the PTT list you downloaded. That data is not part of this package (see Data and licenses).
  • Optional JSON routes for dependent dropdowns (il -> ilçe -> mahalle), disabled by default.

Table of Contents

Requirements

Dependency Version
PHP ^8.2 (with ext-mbstring, ext-zip)
Laravel 11.x / 12.x / 13.x

The PTT list is read with openspout/openspout (MIT), a small streaming spreadsheet reader. It was chosen over PhpSpreadsheet because the list has tens of thousands of rows: OpenSpout reads it row by row with a low memory footprint and has few dependencies.

Installation

composer require ozkanozcan/laravel-turkiye

Auto-discovery registers the service provider and the Turkiye facade. The in-memory API works right away. To use the database features:

php artisan migrate
php artisan turkiye:seed      # embedded provinces and districts into the database
php artisan turkiye:install   # optional: neighbourhoods and postal codes from the PTT list

Publish the config file or the migrations if you want to change them:

php artisan vendor:publish --tag=turkiye-config
php artisan vendor:publish --tag=turkiye-migrations   # then set 'load_migrations' => false in config/turkiye.php
php artisan vendor:publish --tag=turkiye-lang

Usage without a database

use OzkanOzcan\LaravelTurkiye\TurkiyeFacade as Turkiye;   // or the auto-registered alias: Turkiye

Turkiye::provinces();                  // list of 81 Province objects, ordered by plate code

$istanbul = Turkiye::province('istanbul');     // also 'İSTANBUL', 'Istanbul', '34', 34
$istanbul->id;                         // 34 (the plate code)
$istanbul->plate();                    // "34"
$istanbul->slug;                       // "istanbul"
$istanbul->region;                     // "Marmara"
$istanbul->areaCodes;                  // [212, 216]
count($istanbul->districts);           // 39

Turkiye::districts('Ankara');          // 25 District objects; also Turkiye::districts(6)
Turkiye::district('ankara', 'CANKAYA')->name;   // "Çankaya"
Turkiye::districtById(34001)->name;    // "Adalar"
Turkiye::findDistricts('Merkez');      // every district called Merkez, across all provinces

Turkiye::regions();                    // ["Marmara", "Ege", "Akdeniz", "İç Anadolu", "Karadeniz", ...]
Turkiye::provincesIn('Marmara');       // 11 provinces; the region name ignores case and accents

Turkiye::isValidPostalCode('34710');   // true
Turkiye::postalCodeProvince('34710');  // the İstanbul Province
Turkiye::postalCodeMatchesProvince('34710', 'Ankara');   // false

District::$id is the plate code times 1000 plus the position in the province's alphabetical list (34001 is Adalar). A new district can shift the ids of the ones after it, so store the plate code and the name if you need to survive data updates. Province and District objects are JsonSerializable.

Turkish text helpers

PHP's mb_strtoupper() and mb_strtolower() turn i into I and I into i, which is wrong for Turkish. The helpers map i/ı/İ/I by hand and leave the other letters to mb_*.

use OzkanOzcan\LaravelTurkiye\Support\Text;

Text::upper('diyarbakır');             // "DİYARBAKIR"
Text::lower('IŞIK İSTANBUL');          // "ışık istanbul"
Text::title('ÇANKAYA MAHALLESİ');      // "Çankaya Mahallesi"
Text::title("KARA'NIN KÖYÜ");          // "Kara'nın Köyü"
Text::ascii('ÇÜZÜMCÜ');                // "cuzumcu"
Text::slug('Şanlıurfa');               // "sanliurfa"
Text::slug('19 Mayıs / Merkez');       // "19-mayis-merkez"
Text::searchKey('Afyon Karahisar');    // "afyonkarahisar"  (what lookups compare)
Text::compare('Çatalca', 'Cide');      // > 0 (Turkish alphabetical order: c < ç)

The same helpers are available on the facade: Turkiye::upper(), lower(), title(), ascii(), slug().

Validation rules

use OzkanOzcan\LaravelTurkiye\Rules\DistrictBelongsToProvince;
use OzkanOzcan\LaravelTurkiye\Rules\ProvinceExists;
use OzkanOzcan\LaravelTurkiye\Rules\TurkishPostalCode;

$request->validate([
    'province'    => ['required', new ProvinceExists()],
    'district'    => ['required', new DistrictBelongsToProvince('province')],
    'postal_code' => ['required', TurkishPostalCode::inProvince('province')],
]);
  • ProvinceExists: the value is a province name or plate code ("Ankara", "06", 6).
  • DistrictBelongsToProvince('province'): the value is a district of the province named by another field (name or plate code).
  • TurkishPostalCode: five digits whose first two are the plate code of a province. TurkishPostalCode::inProvince('province') also requires the code to belong to the province in another field. A missing or unknown province in that field is left to the province field's own error. Dot notation works (address.province).

Messages are translatable (turkiye::validation.*, English and Turkish included).

Usage with the database

use OzkanOzcan\LaravelTurkiye\Models\District;
use OzkanOzcan\LaravelTurkiye\Models\Neighbourhood;
use OzkanOzcan\LaravelTurkiye\Models\Province;

Province::byPlate('06')->first();
Province::byName('İSTANBUL')->first();         // Turkish-aware: also 'istanbul', 'Afyon Karahisar'
Province::region('İç Anadolu')->get();
Province::find(34)->districts;                 // HasMany
District::byName('cankaya')->first();          // matched on the ASCII slug; byName('can', partial: true) for a prefix
District::byPlate(34)->count();                // 39
Neighbourhood::byPostalCode('06420')->get();   // after turkiye:install
Neighbourhood::byName('ataturk', partial: true)->get();
Neighbourhood::find(1)->district->province;    // BelongsTo

Table names are configurable (turkiye.tables.*, set them before migrating). Province and District use the plate code based ids described above, so there is no auto-increment on them.

turkiye:install

php artisan turkiye:install --file=pk_20241031.xlsx   # a file you downloaded (.xlsx, .ods, .csv, or a .zip holding one)
php artisan turkiye:install                           # download from TURKIYE_PTT_URL
php artisan turkiye:install --url=https://...         # download from another URL
php artisan turkiye:install --dry-run                 # parse and report only
php artisan turkiye:install --fresh                   # delete all neighbourhoods first
php artisan turkiye:install --source-date=2024-10-31

The file needs the columns il, ilçe, semt/bucak/belde, mahalle, posta kodu. They are found by header name, in any order, with extra columns ignored; without a header that order is assumed. Names are uppercase in the source; they are stored in Turkish title case (ÇANKAYA MAHALLESİ becomes Çankaya Mahallesi) and mapped onto the embedded provinces and districts (known aliases such as AFYON, İÇEL, K.MARAŞ and a district written as the province's name for Merkez are accepted).

Rows are never guessed. A province or district that cannot be matched is skipped and listed in the report with its row count, as are rows whose postal code is malformed or does not start with the province's plate code. Repeated rows are stored once (the later one wins). The run, with its source and source date (from the file name pk_YYYYMMDD, the --source-date option, or none), is recorded in the ptt_imports table (PttImport::last()). Running it again updates postal codes in place. turkiye:install also runs the seeder first, so the provinces and districts the rows point at exist.

Read 12 row(s): 6 usable, 2 invalid, 1 duplicate, 3 with unmatched names.
These names could not be matched to a province or district and were skipped:
  ANKARA / ATLANTİS (1 row(s))
  unknown province [ATLANTİS] (2 row(s))
Imported 6 neighbourhood(s). Source date: 2024-10-31.

Unverified live download. When the sibling Rust crate was written, PTT's posta kodu page (https://www.ptt.gov.tr/posta-kodu) offered only an interactive lookup and no downloadable file, and a guessed file URL answered 404. The download code (follow a link to a .zip or .xlsx on the page, size cap, timeout) is tested against a fake HTTP server only. If the live download fails, download the list from PTT yourself and use --file. The column layout is the documented one of PTT's pk_list file and is also tested only against a made-up fixture.

JSON routes

Disabled by default. Enable them with TURKIYE_ROUTES=true (or turkiye.routes.enabled):

Route Result
GET /turkiye/provinces {"data": [{"id": 34, "name": "İstanbul", "slug": "istanbul"}, ...]}
GET /turkiye/provinces/{province}/districts districts of a province (plate code, name or slug), 404 if unknown
GET /turkiye/districts/{district}/neighbourhoods {"data": [{"id", "name", "locality", "postal_code"}, ...]}, needs turkiye:install

The prefix, middleware (default api) and route name prefix are configurable. Provinces and districts are served from memory; only neighbourhoods read the database. The routes are public and unauthenticated: add middleware (for example throttle:60,1) in the config if you need it.

Configuration reference

php artisan vendor:publish --tag=turkiye-config
Key / variable Default Meaning
tables.* provinces, districts, neighbourhoods, ptt_imports Table names used by the migrations and models.
load_migrations true Load the package migrations. Set to false after publishing them.
TURKIYE_PTT_URL https://www.ptt.gov.tr/posta-kodu Where turkiye:install downloads from: the file itself, or a page that links to a .zip / .xlsx file on the same host.
TURKIYE_PTT_TIMEOUT 300 Seconds to wait for the download.
TURKIYE_PTT_MAX_BYTES 209715200 Largest accepted download or spreadsheet (200 MiB).
TURKIYE_ROUTES false Enable the JSON routes.
TURKIYE_ROUTES_PREFIX turkiye URL prefix of the routes.
routes.middleware ['api'] Middleware of the routes.

Testing

composer test

No network is needed. The PTT import is tested with spreadsheets built inside the tests from made-up rows (not PTT data), and the download with Laravel's HTTP fake. Database tests use in-memory SQLite.

Data and licenses

  • The embedded provinces and districts were compiled by the author from public sources and checked against Wikidata (CC0). How is documented in resources/data/SOURCES.md. No third-party dataset was copied. The same files are used by the Rust sibling crate.
  • Neighbourhood (mahalle) and postal code (posta kodu) data comes from the PTT file you obtain yourself (ptt.gov.tr) and is not distributed with this package. Check PTT's terms for your use.
  • This package is not affiliated with PTT.

The code is licensed under the MIT license.

Türkçe özet

ozkanozcan/laravel-turkiye, Laravel 11-13 için il, ilçe, mahalle ve posta kodu verisi sağlar. 81 il (plaka kodu, bölge, alan kodu) ve 973 ilçe pakete gömülüdür ve veritabanı olmadan kullanılabilir; "istanbul", "İSTANBUL" ve "Istanbul" aynı ili bulur. Türkçe İ/ı kurallarına uyan büyük/küçük harf, başlık biçimi ve slug yardımcıları vardır. Posta kodu kuralı (5 hane, ilk iki hane plaka kodu), il kontrolü ve ilçenin ile ait olması kontrolü doğrulama kuralı olarak sunulur.

Mahalle ve posta kodları pakete dahil değildir: PTT'nin posta kodu listesini kendiniz edinip php artisan turkiye:install --file=dosya.xlsx ile veritabanına aktarırsınız. Eşleşmeyen, geçersiz ve tekrarlanan satırlar raporlanır; hiçbir satır tahmin edilmez. --url= ile indirme de desteklenir, ancak PTT şu anda indirilebilir bir dosya sunmadığı için canlı indirme doğrulanmamıştır; dosyayı elle indirip --file kullanın. il -> ilçe -> mahalle açılır listeleri için JSON rotaları vardır ve varsayılan olarak kapalıdır (TURKIYE_ROUTES=true). PTT ile bir bağlantımız yoktur.

composer require ozkanozcan/laravel-turkiye
php artisan migrate
php artisan turkiye:seed

Changelog

See CHANGELOG.md for a history of changes.

Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Commit your changes following Conventional Commits
  4. Push and open a Pull Request against main

Districts change a few times per decade. To update them, edit resources/data/districts.tsv, update the totals pinned in tests/Unit/DataTest.php and note the legal basis in the commit message. Please make sure all tests pass before submitting a PR.

License

MIT © Özkan Özcan - Özcan Teknoloji
See LICENSE for full details.