You build a zip code table in Laravel by choosing what each row represents, generating a migration with the right column types and indexes, modeling the data with Eloquent, and loading it through a seeder or import command. The most important early decision is granularity: one row per postal code is enough for city/state lookup, but you need one row per code-and-place combination once you care about neighborhoods, counties, or multiple cities sharing a ZIP. The steps below cover a practical U.S.-style ZIP code table, and the same pattern adapts to other countries' postal systems.

This guide assumes Laravel 10 or 11 conventions (the two most likely LTS-era choices around late 2026), but the migration and Eloquent patterns are stable across recent versions. Examples use Eloquent and the schema builder in ways that work on MySQL, PostgreSQL, and SQLite unless noted. I'll flag where ZIP-specific quirks—leading zeros, codes spanning states, and lookup performance—change the usual recipe.

Decide what a "zip code" row should represent before writing the migration

ZIP codes are not a clean hierarchy. A single five-digit ZIP can cover parts of more than one city, cross a county line, or straddle a state boundary in dense metro areas. Meanwhile, a city like Springfield can hold dozens of ZIPs. That mismatch is why "just make a zip_codes table with city and state columns" often breaks later.

Three common models, from simplest to most realistic:

Flat lookup. Columns: zip, city, state, latitude, longitude. One row per ZIP. Fast to build; loses information when a ZIP maps to multiple places. Acceptable for shipping estimates or a city autofill. ZIP-to-place junction. A zip_codes table holds the code plus coordinates and maybe county; a separate zip_places (or zip_code_places) table joins each code to one or more city/county/state records. This handles multi-place ZIPs and reverse lookups correctly. Full postal dataset. Add area_codes, timezone, daylight_saving, type (standard, PO box, unique, military), and decommissioned. This mirrors public-domain census-style datasets and supports richer validation.

If you only need to validate "is this a real ZIP?" and show a city, the flat model is fine. If you'll reverse-geocode or report by county, use the junction. The migration below shows the flat-plus-junction approach: a canonical zip_codes table and an optional zip_code_places join so you can start simple and grow.

Prerequisites and a clean starting point

You'll need a working Laravel app with a configured database connection (config/database.php and .env), and you should be able to run php artisan migrate. Nothing here requires extra packages, though a geocoding or dataset-import package can speed up loading. Have your ZIP dataset ready as CSV before seeding—public-domain sources such as the U.S. Census ZCTA files or the freely redistributable ZIP databases commonly used in open-source projects are typical. I can't verify a specific download URL from here, so plan to check the dataset's license and update date yourself.

Two ZIP-specific gotchas to set expectations now:

Leading zeros are real. ZIP 00501 (Holtsville, NY area) must stay 00501, not 501. Store ZIPs as fixed-width strings, not integers. ZIP+4 has a hyphen. The five-digit code plus four-digit add-on (12345-6789) needs either a second column or normalization. I recommend storing the base five digits separately and keeping the full string for display.

Generate and write the migration

Create the migration and model:

Open the create_zip_codes_table migration and define columns. The order that matters: strings for codes, decimals for coordinates, and indexes chosen for the queries you'll actually run.

Why these types:

char(5) for the base ZIP enforces fixed width and preserves leading zeros. unique() prevents duplicate rows per code, which is the core integrity guarantee. decimal(9, 6) holds latitude (max ±90) and longitude (max ±180) with roughly 0.1-meter precision—far more than ZIP centroids need, but safe and portable. Some teams use double; decimals avoid floating drift when you compare coordinates. A nullable state/city keeps the table flexible when a dataset lacks fields, but if your source is complete, make them not null to catch bad imports early.

For the junction table, the foreign key with cascadeOnDelete means deleting a ZIP cleans its place links. The composite index speeds joins filtered by ZIP plus place.

Roll back in the down() method by dropping zip_code_places first, then zip_codes, because of the foreign key:

Model the data with Eloquent relationships and casts

The ZipCode model should expose the relationship and tidy casting. Use a string cast for zip even though it's already a string column—it documents intent and survives driver quirks.

And the junction model:

A subtle but useful relationship: a belongsToMany from a City model through zip_code_places if you normalize cities later. If you keep city as a string, skip it. The point is that the junction decouples "a ZIP's canonical record" from "every place that ZIP touches."

Seed or import the dataset without melting the database

A one-row-at-a-time factory seeder is fine for a few hundred test ZIPs. For a real dataset of ~42,000 ZCTAs or a larger postal file, use chunked imports inside a single transaction or batched commits. Here's a command-based importer that streams CSV and upserts:

Notes on importing well:

str_pad(..., 5, '0', STR_PAD_LEFT) preserves leading zeros when the CSV parser dropped them. upsert with ['zip'] as the unique key makes re-runs idempotent—critical when datasets update quarterly. On MySQL and PostgreSQL this compiles to efficient INSERT ... ON DUPLICATE KEY/ON CONFLICT; SQLite supports it in modern versions. 500-row batches balance memory and round trips. Test with a small slice first, then run the full file. Wrap the whole run in an explicit transaction only if you can tolerate a long lock; otherwise batch commits are safer for large files.

Success check: after running, php artisan tinker and run App\Models\ZipCode::count(); compare to the dataset's row count. Spot-check a known ZIP with a leading zero—ZipCode::where('zip','00501')->first() should return it, not null.

Query correctly: validation, reverse lookup, and the N+1 trap

The table earns its keep in lookups. A few recipes with their performance implications:

Validate a ZIP in a form request. Use a regex that accepts optional ZIP+4, then check existence against the table rather than a hardcoded list:

That where('zip', $zip) hits the unique index—fast on any engine. If you need coordinates, ->first(['zip','latitude','longitude']) avoids selecting unused columns.

Reverse lookup by city and state. This is where indexes matter. Add a composite index in the migration if you'll query by place:

Then ZipCode::where('state','CA')->where('city','Pasadena')->pluck('zip') runs index-only-ish on the composite. Without it, MariaDB and older MySQL will scan the whole table.

Avoid the N+1 problem with the junction. When listing ZIPs with their places, eager load: ZipCode::with('places')->where('state','NY')->paginate(50). Paginating the parent avoids loading tens of thousands of rows; the relationship eager-loads only the current page's children.

Case and spacing. Datasets sometimes store "New York" vs "NEW YORK". Normalize on import (trim, title-case) and, if you allow user search, use whereRaw('LOWER(city) LIKE ?', ['%'.strtolower($q).'%']) sparingly—leading wildcards can't use a standard B-tree index. For serious search, a full-text index or Laravel Scout is the right next step, not a fragile LIKE.

Performance, indexing, and the traps that show up later

At ~42,000 rows the table is small; even a full scan is milliseconds on modern hardware. Performance problems usually come from patterns, not size:

1: Missing index on the lookup column you filter by. The unique zip index covers ZIP lookups; add composite indexes for (state, city) and (state, county) before large reporting queries. 2: Seeding inside a loop with individual create() calls. That's thousands of transactions. Batch with upsert or insert. 3: Storing ZIP as an integer. It works until 00501 becomes 501, then silently mismatches a user's valid input. Fix the column type, don't patch with ltrim. 4: Treating ZIP as a precise point. A ZIP centroid isn't an address; two homes in 90210 can be miles apart. If your feature promises distance accuracy, geocode the actual address and use the ZIP only for coarse grouping.

A quick capacity note: the Census ZCTA file has roughly 33,000 U.S. ZIP Code Tabulation Areas; commercial postal files run around 41,000–42,000 five-digit codes with seasonal changes. Exact counts drift, so treat any specific number as a sanity check, not a target—compare your import count against the metadata row count in your source file.

A reversible troubleshooting path when imports or lookups misbehave

Start with symptoms, not guesses, and prefer changes you can undo.

Leading zeros disappear after import. Symptom: 501 where you expect 00501. Cause: the importer read the column as an integer or a spreadsheet stripped it. Check with ZipCode::where('zip','00501')->exists(); fix the import with str_pad/string casts, and migrate the column to char(5) if it's currently numeric. Duplicate ZIP errors. Symptom: unique constraint violations on re-run. Cause: inserting instead of upserting, or the source has duplicate lines. Switch to upsert($batch, ['zip'], [...]) and de-duplicate the source. Slow city search. Symptom: multi-second queries on state/city filters. Cause: missing composite index. Add index(['state','city']) in a new migration and re-run. Coordinates look wrong. Symptom: points clustered oddly or negative longitudes shown for the U.S. Cause: swapped lat/long columns in the source or sign errors. Verify one known ZIP against a trusted map, then correct the column mapping—don't "fix" values in the database by hand.

If your dataset's license, structure, or coordinate conventions remain unclear after these checks, stop and get the authoritative schema description from the data provider rather than guessing column meanings.

FAQ

Can I skip the junction table if I only show city and state?

Yes. The flat zip_codes table with city, state, and coordinates handles validation and autofill fine. Add the junction only when you must represent multiple cities or counties per ZIP, or report by county while displaying city.

Should ZIP be a primary key?

You can use char(5) as the primary key for the flat table, but surrogate id plus a unique zip keeps foreign keys simple and survives the rare code reassignment. Keep the unique index either way.

How do I handle ZIP+4?

Store the base five digits in zip and the full hyphenated code in zip_plus_four (or split into a four-digit column). Validate the full string with the regex above, and look up using the base code so ZIP+4 input still resolves.

Does this work for non-U.S. postal codes?

The pattern transfers; the fields change. UK postcodes need alphanumeric strings with spaces, Canada uses a letter-digit format, and both need broader length columns. The stickiest part is that some countries' postal codes aren't a clean one-to-one with a place, so the junction table becomes more valuable, not less.