PHPackages                             awaisjameel/laravel-address-parser - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. awaisjameel/laravel-address-parser

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

awaisjameel/laravel-address-parser
==================================

A Laravel package for parsing US addresses.

1.0.0(6mo ago)0467↓33.3%[3 PRs](https://github.com/awaisjameel/laravel-address-parser/pulls)MITPHPPHP 7.4|^8.2CI passing

Since Nov 4Pushed 2mo agoCompare

[ Source](https://github.com/awaisjameel/laravel-address-parser)[ Packagist](https://packagist.org/packages/awaisjameel/laravel-address-parser)[ Docs](https://github.com/awaisjameel/laravel-address-parser)[ GitHub Sponsors](https://github.com/awaisjameel)[ RSS](/packages/awaisjameel-laravel-address-parser/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (12)Versions (5)Used By (0)

Laravel Address Parser
======================

[](#laravel-address-parser)

**Smart, opinionated parsing of single‑line US postal addresses into structured components for Laravel.**

[![Latest Version on Packagist](https://camo.githubusercontent.com/f15a96b3c31fa95128c11cb65ee79efeb37dbf71b4cc827549005b4516f1a7ab/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f61776169736a616d65656c2f6c61726176656c2d616464726573732d7061727365722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/awaisjameel/laravel-address-parser)[![GitHub Tests Action Status](https://camo.githubusercontent.com/ebd15ca88270d67ded7d1e58ff0a1d0f0618769c3227346289a6ced28c2fd382/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f61776169736a616d65656c2f6c61726176656c2d616464726573732d7061727365722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/awaisjameel/laravel-address-parser/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/f99f1a7a2b8b3d954bb482e846debfff311857d9b6e2721bc52b35e850b24875/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f61776169736a616d65656c2f6c61726176656c2d616464726573732d7061727365722f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/awaisjameel/laravel-address-parser/actions?query=workflow%3A)[![Total Downloads](https://camo.githubusercontent.com/937b56fd8e0e1b4e8d7afaaab1c266a3a7f01362322d3e4b8467a12816c5bea5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f61776169736a616d65656c2f6c61726176656c2d616464726573732d7061727365722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/awaisjameel/laravel-address-parser)

Laravel Address Parser helps you take messy user‑submitted single line US addresses and split them into reliable fields: `address1`, `address2` (unit), `city`, `state`, `zip` and optionally `county`. It applies pragmatic heuristics—street suffix detection, unit indicator extraction, normalization (whitespace + periods), and validation of state + ZIP formats—without depending on external APIs. Ideal for form ingestion, ETL pipelines, quick data cleanup, and pre‑validation before geocoding.

> Not a USPS CASS certified normalizer. It doesn't validate that an address physically exists; it simply parses and validates format.

---

Table of Contents
-----------------

[](#table-of-contents)

1. [Features](#features)
2. [Requirements](#requirements)
3. [Installation](#installation)
4. [Quick Start](#quick-start)
5. [Usage Examples](#usage-examples)
6. [Facade, DI &amp; Helper Patterns](#facade-di--helper-patterns)
7. [Parsing Logic &amp; Heuristics](#parsing-logic--heuristics)
8. [County Parsing](#county-parsing)
9. [Validation Utilities](#validation-utilities)
10. [Formatting Addresses](#formatting-addresses)
11. [Configuration](#configuration)
12. [Error Handling](#error-handling)
13. [Edge Cases &amp; Limitations](#edge-cases--limitations)
14. [Testing](#testing)
15. [Performance](#performance)
16. [Roadmap](#roadmap)
17. [Contributing](#contributing)
18. [Security](#security)
19. [Support Us](#support-us)
20. [Credits](#credits)
21. [License](#license)

---

Features
--------

[](#features)

- ✅ Parse single‑line US addresses with or without commas
- ✅ Detect and extract unit indicators (`APT`, `STE`, `#12`, `FLOOR`, etc.)
- ✅ Supports ZIP (5‑digit) and ZIP+4 (extended) formats
- ✅ Validates US state abbreviations (full 50 + DC)
- ✅ Optional county parsing via comma‑separated form
- ✅ Normalizes periods after abbreviations (`St.` → `St`), collapses excess whitespace
- ✅ Graceful formatting back to a one‑line address
- ✅ Clear, typed exception (`AddressParsingException`) for invalid cases
- ✅ Simple, framework‑friendly (pure static methods), zero external API calls
- ✅ Battle‑tested with [Pest](https://pestphp.com/) test suite

---

Requirements
------------

[](#requirements)

ComponentVersionPHP7.4 or ^8.2Laravel (illuminate/contracts)^10^11^12Extension dependenciesNone beyond standard PHP + mbstring---

Installation
------------

[](#installation)

Install via Composer:

```
composer require awaisjameel/laravel-address-parser
```

The package auto‑discovers. No manual provider registration required.

### Optional: Publish Config

[](#optional-publish-config)

Currently the config file is a placeholder for future tuning (custom suffixes, unit indicators, etc.). You can publish it now:

```
php artisan vendor:publish --tag="laravel-address-parser-config"
```

Published file at `config/address-parser.php`:

```
return [
	// Reserved for future customization: e.g. 'extra_street_suffixes' => [],
	// 'extra_unit_indicators' => [],
];
```

> No migrations or views are shipped (ignore earlier generic template tags).

---

Quick Start
-----------

[](#quick-start)

```
use Awaisjameel\LaravelAddressParser\LaravelAddressParser;

$parsed = LaravelAddressParser::parseAddressString('500 Elm Avenue Apt 4B Metropolis NY 10001');

/* Result:
[
  'address1' => '500 Elm Avenue',
  'address2' => 'APT 4B',
  'city'     => 'Metropolis',
  'state'    => 'NY',
  'zip'      => '10001',
  'county'   => null,
]
*/
```

---

Usage Examples
--------------

[](#usage-examples)

### 1. Basic Parsing (No Commas)

[](#1-basic-parsing-no-commas)

```
$parsed = LaravelAddressParser::parseAddressString('77 Broadway St #12 Gotham NJ 07001');
// address2 is '#12'
```

### 2. Comma‑Separated

[](#2-commaseparated)

```
$parsed = LaravelAddressParser::parseAddressString('1600 Pennsylvania Avenue NW, Washington, DC 20500-0003');
```

### 3. With County (If Provided)

[](#3-with-county-if-provided)

```
$parsed = LaravelAddressParser::parseAddressStringWithCounty('123 Main St, Springfield, Greene, MO 65804');
// county => 'Greene'
```

### 4. County Method Without County

[](#4-county-method-without-county)

```
$parsed = LaravelAddressParser::parseAddressStringWithCounty('1600 Pennsylvania Avenue NW, Washington, DC 20500');
// county => null
```

### 5. Format Back to One Line

[](#5-format-back-to-one-line)

```
$formatted = LaravelAddressParser::formatAddress([
  'address1' => '123 Main St',
  'address2' => 'APT 4B',
  'city'     => 'Springfield',
  'state'    => 'IL',
  'zip'      => '62704',
]);
// "123 Main St APT 4B, Springfield, IL 62704"
```

### 6. Validation Helpers

[](#6-validation-helpers)

```
LaravelAddressParser::isValidState('TX');     // true
LaravelAddressParser::isValidZipCode('12345-6789'); // true
LaravelAddressParser::getValidStates();       // [ 'AL', 'AK', ... ]
```

---

Facade, DI &amp; Helper Patterns
--------------------------------

[](#facade-di--helper-patterns)

Because all methods are static, you can call the class directly. A facade alias `LaravelAddressParser` is registered; if you prefer the facade style:

```
use LaravelAddressParser; // Facade alias

$parsed = LaravelAddressParser::parseAddressString('500 Elm Avenue Apt 4B Metropolis NY 10001');
```

Dependency injection is not required, but you can wrap this in your own service if you want to enforce non‑static boundaries for test isolation.

---

Parsing Logic &amp; Heuristics
------------------------------

[](#parsing-logic--heuristics)

1. Normalize input: trim, collapse whitespace, remove trailing punctuation, strip periods after known abbreviations.
2. Extract trailing `STATE ZIP` using regex. Validate both.
3. Before the state/ZIP segment:
    - If no commas: locate rightmost known street suffix, everything after → city.
    - If commas: last comma part → city; remaining → address lines.
4. Unit detection:
    - Detect explicit unit parts after street suffix (e.g. `Apt 4B`, `#12`).
    - Handles units embedded at end of `address1` or separated by comma.
5. Normalizes unit casing (except leading `#`).
6. Returns structured array including a nullable `county` when parsed via county method.

Recognized street suffixes (subset): `ST`, `AVE`, `RD`, `DR`, `LN`, `CT`, `CIR`, `BLVD`, `PKWY`, `TRAIL`, `HWY`, `WAY`, `PL`, `LOOP`, `TER`, `EXPY`, etc.

Recognized unit indicators: `APT`, `SUITE`, `STE`, `UNIT`, `FLOOR`, `ROOM`, `BLDG`, `#`, `LOT`, `SPACE`, etc.

---

County Parsing
--------------

[](#county-parsing)

Use `parseAddressStringWithCounty()` for either format:

1. `Street, City, County, ST ZIP`
2. `Street, City, ST ZIP` (county omitted → `county => null`)

If fewer than 3 comma‑separated parts exist (excluding state/ZIP) an exception is thrown.

---

Validation Utilities
--------------------

[](#validation-utilities)

MethodPurpose`isValidZipCode(string $zip)`5‑digit or ZIP+4 pattern `12345` / `12345-6789``isValidState(string $state)`Valid two‑letter US state (inclusive of DC)`getValidStates()`Returns internal list of state abbreviationsThese do not consult external APIs; they are format checks only.

---

Formatting Addresses
--------------------

[](#formatting-addresses)

`formatAddress(array $components): string` builds a single line string from parsed parts. Missing `address2` is skipped; missing `address1` results in `City, ST ZIP` only.

```
$oneLine = LaravelAddressParser::formatAddress($parsed);
```

---

Configuration
-------------

[](#configuration)

Currently no runtime options are exposed. Future versions may allow:

- Extending street suffix list
- Extending unit indicator list
- Custom validation strategy or USPS API integration hooks

Feel free to open an issue with your use case.

---

Error Handling
--------------

[](#error-handling)

Parsing failures throw `Awaisjameel\LaravelAddressParser\AddressParsingException` with a human‑readable message. Common triggers:

- Empty or "0" input
- Cannot locate valid trailing `STATE ZIP`
- Invalid state abbreviation (e.g. `ZZ`)
- Invalid ZIP format
- Missing city segment
- Cannot identify street suffix when required

Always wrap user‑submitted data:

```
try {
	$parsed = LaravelAddressParser::parseAddressString($raw);
} catch (AddressParsingException $e) {
	// Log, show validation error, fallback, etc.
}
```

---

Edge Cases &amp; Limitations
----------------------------

[](#edge-cases--limitations)

ScenarioBehaviorMissing street suffix &amp; no commasThrows exceptionExcess whitespaceNormalizedPeriods after abbreviations (`St.`)RemovedMixed case units (`aPt 4b`)Uppercased →`APT 4B`Standalone `#12` unitPreserved exactlyNon‑US addressesLikely rejected (state + ZIP fail)Addresses without house numberUsually rejected unless suffix detection passes heuristicsPO BoxesParsed as street if suffix logic permits (e.g.`PO BOX 123`)Not a full canonicalizer: it won't expand `NW` to `Northwest`, or validate delivery points.

---

Testing
-------

[](#testing)

Run the full test suite (Pest):

```
composer test
```

Or with coverage:

```
composer test-coverage
```

Static analysis:

```
composer analyse
```

Code style (Laravel Pint):

```
composer format
```

---

Performance
-----------

[](#performance)

All operations are in‑memory string functions &amp; a few regex matches. Suitable for real‑time form handling. For bulk ETL (hundreds of thousands of rows) you can batch process safely; memory footprint is minimal.

Micro‑optimizations (e.g. caching compiled regex) are intentionally deferred until a real hotspot is demonstrated.

---

Roadmap
-------

[](#roadmap)

- Optional configuration for custom suffix/unit lists
- USPS address standardization adapter
- Geocoding integration hooks
- Bulk parsing helper with per‑record error collection
- Locale expansion (Canadian, UK parsing) via strategy interfaces

Have a request? Open an issue.

---

Contributing
------------

[](#contributing)

Contributions are welcome! Please:

1. Fork &amp; create a feature branch
2. Add/adjust tests for new behavior
3. Run: `composer analyse`, `composer format`, `composer test`
4. Open a PR describing rationale &amp; trade‑offs

For architectural changes, open an issue first for discussion.

---

Security
--------

[](#security)

If you discover a security vulnerability (e.g. pathological regex input leading to DoS), please email the author or open a private advisory. Avoid posting exploits publicly until a fix is released.

This library does not execute external processes or perform network calls, and stores no secrets.

---

Support Us
----------

[](#support-us)

If you find this package useful, consider supporting its development make sure to give a star on GitHub!

---

Credits
-------

[](#credits)

- [awaisjameel](https://github.com/awaisjameel)
- Inspired by pragmatic parsing approaches in many OSS data-cleanup tools

---

License
-------

[](#license)

Released under the MIT License. See [`LICENSE.md`](LICENSE.md).

---

FAQ
---

[](#faq)

### Does it validate an address actually exists?

[](#does-it-validate-an-address-actually-exists)

No. It validates format only. For existence use USPS, Smarty, Google, etc.

### Will it parse multi‑line addresses?

[](#will-it-parse-multiline-addresses)

Only single‑line strings. Pre‑join lines ("address1 address2") before parsing, or use the county method if needed.

### Why static methods?

[](#why-static-methods)

Low ceremony; no state. You can wrap them if you prefer dependency injection.

### Is the heuristics list exhaustive?

[](#is-the-heuristics-list-exhaustive)

It covers common US street suffixes &amp; unit indicators. You can extend in the future via config once exposed.

### Can I disable normalization?

[](#can-i-disable-normalization)

Not yet. Planned via config.

---

Example End‑to‑End Form Handling
--------------------------------

[](#example-endtoend-form-handling)

```
try {
	$parsed = LaravelAddressParser::parseAddressString(request('address_line'));

	// Persist
	CustomerAddress::create([
		'address1' => $parsed['address1'],
		'address2' => $parsed['address2'],
		'city'     => $parsed['city'],
		'state'    => $parsed['state'],
		'zip'      => $parsed['zip'],
		'county'   => $parsed['county'],
		'raw'      => request('address_line'),
	]);
} catch (AddressParsingException $e) {
	return back()->withErrors(['address_line' => $e->getMessage()]);
}
```

---

Happy parsing! 📨

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance78

Regular maintenance activity

Popularity17

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 84.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

195d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8478f5cd00831255bda5f4ab259a8761a8001142756ab90bf8804388a78b2036?d=identicon)[awaisjameel](/maintainers/awaisjameel)

---

Top Contributors

[![awaisjameel](https://avatars.githubusercontent.com/u/9046343?v=4)](https://github.com/awaisjameel "awaisjameel (11 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laravelAwaisJameellaravel-address-parserus-address-parseraddress-parser

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/awaisjameel-laravel-address-parser/health.svg)

```
[![Health](https://phpackages.com/badges/awaisjameel-laravel-address-parser/health.svg)](https://phpackages.com/packages/awaisjameel-laravel-address-parser)
```

###  Alternatives

[spatie/laravel-markdown

A highly configurable markdown renderer and Blade component for Laravel

4053.4M35](/packages/spatie-laravel-markdown)[vormkracht10/laravel-mails

Laravel Mails can collect everything you might want to track about the mails that has been sent by your Laravel app.

24149.7k](/packages/vormkracht10-laravel-mails)[spatie/laravel-markdown-response

Serve markdown versions of your HTML pages to AI agents and bots

6512.6k](/packages/spatie-laravel-markdown-response)[rajentrivedi/tokenizer-x

TokenizerX calculates required tokens for given prompt

91214.0k3](/packages/rajentrivedi-tokenizer-x)[prezet/prezet

Prezet: Markdown Blogging for Laravel

2969.8k2](/packages/prezet-prezet)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
