PHPackages                             dominservice/data\_locale\_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. [Localization &amp; i18n](/categories/localization)
4. /
5. dominservice/data\_locale\_parser

ActiveLibrary[Localization &amp; i18n](/categories/localization)

dominservice/data\_locale\_parser
=================================

Data Locale Parser is a package for Laravel 9 | 10 | 11 | 12 | 13, which lists all countries, currencies and languages, with names and ISO 3166 codes in all languages and data formats.

3.0.1(1mo ago)01462MITPHPPHP ^8.0.2

Since Jan 6Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/dominservice/data_locale_parser)[ Packagist](https://packagist.org/packages/dominservice/data_locale_parser)[ Docs](https://github.com/dominservice/data_locale_parser)[ RSS](/packages/dominservice-data-locale-parser/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (10)Dependencies (4)Versions (28)Used By (2)

Data Locale Parser
==================

[](#data-locale-parser)

[![Latest Version](https://camo.githubusercontent.com/6bb274ccb0a7c960eadadaa5f44c958740373bd66f49035bde9ac9768b202294/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f646f6d696e736572766963652f646174615f6c6f63616c655f7061727365722e7376673f7374796c653d666c61742d737175617265)](https://github.com/dominservice/data_locale_parser/releases)[![Total Downloads](https://camo.githubusercontent.com/ec56d5359a275f3e3fce3ec54a05500aa96ef2da4a35fd660539973ddc171182/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f646f6d696e736572766963652f646174615f6c6f63616c655f7061727365722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/dominservice/data_locale_parser)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)

Data Locale Parser is a package for Laravel 9, 10, 11, 12 and 13, which lists all countries, currencies and languages, with names and ISO 3166-1 codes in all languages and data formats.

Compatibility
-------------

[](#compatibility)

Package versionSupported Laravel versionsPHP`3.x``9.x`, `10.x`, `11.x`, `12.x`, `13.x``^8.0.2``< 3.0.0`legacy releasessee the `composer.json` in the selected tagVersion `3.x` is the officially supported release line for Laravel 9 through 13.

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

[](#installation)

Require package via Composer:

```
composer require dominservice/data_locale_parser:^3.0
```

Usage
-----

[](#usage)

- Locale (en, en\_US, fr, fr\_CA...)
    - If no locale is given (or if it is set to null), then it will default to 'en'

Declare ussage

```
use \Dominservice\DataLocaleParser\DataParser;
```

(...)

```
private $dataParser;
```

(...)

```
public function __construct() {
    $this->dataParser = new DataParser();
}
```

Get all countries

```
$this->dataParser->getListCountries('en');
```

Get all currencies

```
$this->dataParser->getListCurrencies('en');
```

Get all Languages

```
$this->dataParser->getListLanguages('en');
```

All lists return a collection

---

Get country

```
$this->dataParser->getCountry('PL', 'en');
```

Get currency

```
$this->dataParser->getCurrency('PLN', 'en');
```

Get Language

```
$this->dataParser->geLanguage('pl_PL', 'en');
```

Format an address based on country-specific format

```
// Address data with keys like address, address2, city, subdivision, postalCode, countryCode
$addressData = [
    'address' => '1234 Some St.',
    'address2' => 'Floor #67',
    'city' => 'San Francisco',
    'subdivision' => 'CA',
    'postalCode' => '94105',
    'countryCode' => 'US'
];

// Basic address formatting (returns an array of address lines)
$formattedAddress = $this->dataParser->formatAddress($addressData);

// Format address with additional parameters
$formattedAddressComplete = $this->dataParser->formatAddress(
    $addressData,                    // Address data
    'John Doe',                      // Name
    'Example Company Ltd.',          // Company name
    'GB123456789',                   // VAT number
    '+1 (123) 456-7890',             // Phone number
    ['Customer ID: 12345']           // Additional fields
);

// Format address with just some parameters (others will be null)
$formattedAddressPartial = $this->dataParser->formatAddress(
    $addressData,                    // Address data
    null,                            // No name
    'Example Company Ltd.',          // Company name
    null,                            // No VAT number
    '+1 (123) 456-7890'              // Phone number
);
```

### Address Format Keys

[](#address-format-keys)

The following keys can be used in the address data array for the `formatAddress` function:

KeyDescriptionExample`address`Primary address line (street address)1234 Some St.`address2`Secondary address lineFloor #67`address3`Tertiary address lineUnit #123`city`City nameSan Francisco`subdivision`State, province, or regionCA`postalCode`Postal or ZIP code94105`countryCode`ISO 3166-1 Alpha-2 country code (required)USThe function will format the address according to the country-specific format based on the `countryCode`. If a specific country format is not available, it will use the international format.

### Additional Address Parameters

[](#additional-address-parameters)

The `formatAddress` function accepts several additional parameters beyond the basic address data:

ParameterTypeDescriptionExample`name`stringPerson's name to include at the beginning of the addressJohn Doe`companyName`stringCompany name to include in the addressExample Company Ltd.`vatNumber`stringVAT identification numberGB123456789`phoneNumber`stringContact phone number+1 (123) 456-7890`additionalFields`arrayArray of additional text lines to include\['Customer ID: 12345'\]These additional parameters will be included in the formatted address in the following order:

1. Name (if provided)
2. Company name (if provided)
3. VAT number (if provided, prefixed with "VAT: ")
4. Standard address lines (formatted according to country format)
5. Phone number (if provided)
6. Any additional fields (in the order they appear in the array)

If you have collected all data, you make use this code

```
 $this->dataParser->parseAllDataPerCountry('pl_PL');
```

Then You get

```
Illuminate\Support\Collection {▼
  #items: [
    0 => {#1992 ▼
      +"so": "PL"
      +"iso3": "POL"
      +"iso_nr": "616"
      +"fips": "PL"
      +"continent": "EU"
      +"tld": ".pl"
      +"phone": "48"
      +"postal_code_format": "##-###"
      +"postal_code_regex": "^\d{2}-\d{3}$"
      +"currency": {#1991 ▼
        +"name": "złoty polski"
        +"code": "PLN"
        +"symbol": "zł"
      }
      +"languages": array:1 [▼
        "pl" => "polski"
      ]
      +"country": "Polska"
      +"subdivision_iso3166": Illuminate\Support\Collection {#2275 ▼
        #items: array:16 [▼
          "PL-02" => array:2 [▼
            "name" => "Dolnośląskie"
            "name_ascii" => "Dolnoslaskie"
          ]
          "PL-04" => array:2 [▼
            "name" => "Kujawsko-pomorskie"
            "name_ascii" => "Kujawsko-pomorskie"
          ]
          "PL-06" => array:2 [▼
            "name" => "Lubelskie"
            "name_ascii" => "Lubelskie"
          ]
          "PL-08" => array:2 [▼
            "name" => "Lubuskie"
            "name_ascii" => "Lubuskie"
          ]
          "PL-10" => array:2 [▼
            "name" => "Łódzkie"
            "name_ascii" => "Lodzkie"
          ]
          "PL-12" => array:2 [▼
            "name" => "Małopolskie"
            "name_ascii" => "Malopolskie"
          ]
          "PL-14" => array:2 [▼
            "name" => "Mazowieckie"
            "name_ascii" => "Mazowieckie"
          ]
          "PL-16" => array:2 [▼
            "name" => "Opolskie"
            "name_ascii" => "Opolskie"
          ]
          "PL-18" => array:2 [▼
            "name" => "Podkarpackie"
            "name_ascii" => "Podkarpackie"
          ]
          "PL-20" => array:2 [▼
            "name" => "Podlaskie"
            "name_ascii" => "Podlaskie"
          ]
          "PL-22" => array:2 [▼
            "name" => "Pomorskie"
            "name_ascii" => "Pomorskie"
          ]
          "PL-24" => array:2 [▼
            "name" => "Śląskie"
            "name_ascii" => "Slaskie"
          ]
          "PL-26" => array:2 [▶]
          "PL-28" => array:2 [▼
            "name" => "Warmińsko-mazurskie"
            "name_ascii" => "Warminsko-mazurskie"
          ]
          "PL-30" => array:2 [▼
            "name" => "Wielkopolskie"
            "name_ascii" => "Wielkopolskie"
          ]
          "PL-32" => array:2 [▼
            "name" => "Zachodniopomorskie"
            "name_ascii" => "Zachodniopomorskie"
          ]
        ]
      }
    }

    ...
}
```

You may get one country full data

```
 $this->dataParser->parseAllDataPerCountry('pl_PL', 'PL');
```

Language Handling Middleware
----------------------------

[](#language-handling-middleware)

This package includes a middleware for handling language detection from URL paths and request headers. This allows you to create routes with language prefixes (e.g., `/en/page`, `/pl/page`) and automatically set the application locale based on the URL or header.

### Configuration

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --provider="Dominservice\DataLocaleParser\DataLocaleParserServiceProvider" --tag="config"
```

This will create a `config/data_locale_parser.php` file with the following options:

```
return [
    // Whether to detect language from URL
    'detect_from_url' => true,

    // Whether to use cookies for language storage
    // If true, the language preference will be stored in a cookie
    // URL locale detection still has priority over cookies
    'use_cookies' => false,

    // Whether to detect language from header
    'detect_from_header' => true,

    // The name of the header to check for language
    'header_name' => 'Accept-Language',

    // Default locale if no language is detected
    'default_locale' => 'en',

    // Locale without URL prefix. If null, default_locale is used.
    'unprefixed_locale' => null,

    // Allowed locales
    'allowed_locales' => [
        'en',
        'pl',
        'de',
        'fr',
        'es',
        'en_GB',
        'en_US',
    ],

    // API prefixes
    'api_prefixes' => [
        'api',
    ],

    // Cookie settings
    'cookie_name' => 'language',
    'cookie_lifetime' => 43200, // 30 days

    // Language change route
    // This route will be registered automatically by the service provider
    'language_change_route' => 'change-language',
];
```

### Usage

[](#usage-1)

Register the middleware in your `app/Http/Kernel.php` file:

```
protected $routeMiddleware = [
    // Other middleware...
    'language' => \Dominservice\DataLocaleParser\Http\Middleware\LanguageMiddleware::class,
];
```

and

```
protected $middlewareGroups = [
    'web' => [
        // Other middleware...
        \Dominservice\DataLocaleParser\Http\Middleware\SetLocaleMiddleware::class,
    ],
];
```

#### Cookie Encryption

[](#cookie-encryption)

By default, Laravel encrypts all cookies. If you're using cookies for language storage (`use_cookies` set to `true`), you need to exclude the language cookie from encryption. Otherwise, the middleware might not be able to read the cookie correctly.

Add the language cookie name to the `$except` array in your `app/Http/Middleware/EncryptCookies.php` file:

```
namespace App\Http\Middleware;

use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class EncryptCookies extends Middleware
{
    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array
     */
    protected $except = [
        'language', // Add the language cookie name here (use the value from your config)
    ];
}
```

If you've changed the cookie name in your configuration, make sure to use that name instead of 'language'.

#### Cookie Handling

[](#cookie-handling)

This package sets cookies directly on the response object to ensure they are properly included in the response. The package automatically applies the `web` middleware group to its routes to ensure that cookies work correctly.

Apply the middleware to your routes:

```
// Apply to specific routes
Route::get('/{any}', 'HomeController@index')->middleware('language')->where('any', '.*');

// Apply to route groups
Route::middleware(['language'])->group(function () {
    Route::get('/', 'HomeController@index');
    Route::get('/{any}', 'HomeController@index')->where('any', '.*');
});

// Apply to API routes
Route::prefix('api')->middleware(['language'])->group(function () {
    Route::get('/{lang}/users', 'Api\UserController@index');
});
```

### How It Works

[](#how-it-works)

1. **URL Detection**: The middleware checks if the first segment of the URL path is a valid language code. For API routes (URLs starting with a prefix defined in `api_prefixes`), it checks the second segment.
2. **Header Detection**: If URL detection is disabled or fails, the middleware checks the request header specified in the configuration.
3. **Default Locale**: If no language is detected from the URL or header, the middleware uses the default locale specified in the configuration.
4. **Cookie Storage**: If `use_cookies` is enabled, the language preference will be stored in a cookie. Explicit locale from URL still has priority over the cookie. If the current request has no locale prefix, the package uses `unprefixed_locale` or falls back to `default_locale`.

### Changing the Language

[](#changing-the-language)

The package automatically registers a route for changing the language. By default, this route is `/change-language/{language}`, but you can customize it in the configuration.

To create a language switcher in your application, you can use the following example:

```

    @foreach(config('data_locale_parser.allowed_locales') as $locale)

                {{ strtoupper($locale) }}

    @endforeach

```

When a user clicks on a language link, the following happens:

1. The language is validated against the allowed locales and the language database.
2. If valid, the language is set as the application locale.
3. If `use_cookies` is enabled, the language preference is stored in a cookie.
4. The user is redirected back to the previous page using one of the following methods:
    - **Route Name-Based Redirection**: If the previous page has a named route with a locale prefix (e.g., `en.contact`), the controller will replace the locale in the route name and redirect to the new route with the same parameters. This allows for path translation (e.g., `/kontakt` to `/contact`) when your routes are properly localized.
    - **URL Segment Manipulation**: If route name-based redirection fails or the route doesn't have a name, the controller falls back to URL segment manipulation:
        - If the target language is the unprefixed locale, the language prefix is removed from the URL.
        - Otherwise, the language prefix is updated or added to the URL.

This allows you to create a seamless language switching experience for your users, with or without showing the language in the URL, and with support for path translation when using named routes.

### Setting Up Localized Routes

[](#setting-up-localized-routes)

To take advantage of the route name-based redirection and path translation, you need to set up your routes with locale prefixes in their names. Here's an example:

```
// routes/web.php

// English routes
Route::prefix('en')->name('en.')->middleware(['language'])->group(function () {
    Route::get('/', 'HomeController@index')->name('home');
    Route::get('/contact', 'ContactController@index')->name('contact');
    Route::get('/about', 'AboutController@index')->name('about');
});

// Polish routes
Route::prefix('pl')->name('pl.')->middleware(['language'])->group(function () {
    Route::get('/', 'HomeController@index')->name('home');
    Route::get('/kontakt', 'ContactController@index')->name('contact');
    Route::get('/o-nas', 'AboutController@index')->name('about');
});

// German routes
Route::prefix('de')->name('de.')->middleware(['language'])->group(function () {
    Route::get('/', 'HomeController@index')->name('home');
    Route::get('/kontakt', 'ContactController@index')->name('contact');
    Route::get('/uber-uns', 'AboutController@index')->name('about');
});
```

With this setup, when a user switches from Polish to English while on the `/pl/kontakt` page, they will be redirected to `/en/contact` instead of just changing the language prefix.

Helper Functions
----------------

[](#helper-functions)

This package includes several helper functions to make working with localized routes and URLs easier. These functions are automatically loaded when you install the package.

### RTL Detection

[](#rtl-detection)

```
locale_is_rtl(?string $locale = null): bool
```

Checks if a locale is RTL (Right-to-Left). If no locale is provided, it uses the current application locale.

```
if (locale_is_rtl('ar')) {
    // Arabic is an RTL language
}

if (locale_is_rtl()) {
    // The current locale is an RTL language
}
```

You can configure which locales are considered RTL in the `config/data_locale_parser.php` file:

```
'locale_rtl' => [
    'ar',    // Arabic
    'fa',    // Persian (Farsi)
    'he',    // Hebrew
    'ur',    // Urdu
    'yi',    // Yiddish
    // ... other RTL languages
],
```

### Route Translation

[](#route-translation)

```
get_translated_route(string $locale, string $key): string
```

Gets a translated route key for a specific locale. This is useful for translating route names or segments.

```
$translatedKey = get_translated_route('pl', 'contact');
// Returns 'kontakt' if a translation exists, otherwise 'pl.contact'
```

### Localized Routes

[](#localized-routes)

```
route_current_locale(string $route, mixed $parameters = [], bool $absolute = true): string
```

Generates a URL to a named route for the current locale.

```
$url = route_current_locale('contact');
// If the current locale is 'en', returns URL for 'en.contact'
```

```
route_locale(string $locale, string $route, mixed $parameters = [], bool $absolute = true): string
```

Generates a URL to a named route for a specific locale.

```
$url = route_locale('pl', 'contact');
// Returns URL for 'pl.contact'
```

### Route Checking

[](#route-checking)

```
is_route_current_locale(mixed ...$patterns): bool
```

Checks if the current route name matches any of the given patterns for the current locale.

```
if (is_route_current_locale('contact', 'about')) {
    // Current route is either 'en.contact' or 'en.about' (assuming current locale is 'en')
}
```

### URL Localization

[](#url-localization)

```
get_localized_url(string $locale): string
```

Gets the URL for the current page in a different locale. This function tries to use route name-based redirection first, and falls back to URL segment manipulation if that fails.

```
$plUrl = get_localized_url('pl');
// If current URL is '/en/contact', returns '/pl/kontakt' (if route names are properly set up)
```

Examples
--------

[](#examples)

For more advanced usage examples, check out the [examples directory](examples/). It contains sample code demonstrating various features of the library, including:

- Enhanced language full data methods with caching, custom display locales, and advanced filtering
- Single language data retrieval
- Language handling middleware usage
- And more

Credits
-------

[](#credits)

- [UN/LOCODE Country Subdivisions ISO 3166-2](https://unece.org/trade/uncefact/unlocode-country-subdivisions-iso-3166-2)
- [Monarobase/country-list](https://github.com/Monarobase/country-list)
- [umpirsky/language-list](https://github.com/umpirsky/language-list)
- [umpirsky/locale-list](https://github.com/umpirsky/locale-list)
- [ipregistry/iso3166](https://github.com/ipregistry/iso3166)

---

Support
-------

[](#support)

### Support this project (Ko‑fi)

[](#support-this-project-kofi)

If this package saves you time, consider buying me a coffee:  — thank you!

---

License
-------

[](#license)

MIT © Dominservice

###  Health Score

48

—

FairBetter than 94% of packages

Maintenance93

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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

Every ~73 days

Recently: every ~62 days

Total

27

Last Release

36d ago

Major Versions

1.7.0 → 2.0.02025-07-13

2.2.1 → 3.0.02026-04-02

PHP version history (3 changes)1.0.0PHP &gt;=7.2

1.3.0PHP &gt;=7.1.3

3.0.0PHP ^8.0.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/9d67c041316385020aafb7eef9f11971d6fad80a11a44f4078273bda6890722d?d=identicon)[dominservice](/maintainers/dominservice)

---

Top Contributors

[![dominservice](https://avatars.githubusercontent.com/u/13433147?v=4)](https://github.com/dominservice "dominservice (1 commits)")

---

Tags

phplaravellanguagescountriescurrenciescountry listcurrencies listdata parserlanguages listumpirsky

### Embed Badge

![Health badge](/badges/dominservice-data-locale-parser/health.svg)

```
[![Health](https://phpackages.com/badges/dominservice-data-locale-parser/health.svg)](https://phpackages.com/packages/dominservice-data-locale-parser)
```

###  Alternatives

[mcamara/laravel-localization

Easy localization for Laravel

3.5k9.1M112](/packages/mcamara-laravel-localization)[nnjeim/world

Laravel countries, states, cities, currencies, languages and IP geolocation

970361.2k3](/packages/nnjeim-world)[io238/laravel-iso-countries

Ready-to-use Laravel models and relations for country (ISO 3166), language (ISO 639-1), and currency (ISO 4217) information with multi-language support.

5462.3k](/packages/io238-laravel-iso-countries)[macmotp/locale

A curated library to handle locale in PHP

507.1k](/packages/macmotp-locale)[juanparati/iso-codes

A PHP library that provides ISO codes, currencies, languages, timezones and additional geopolitical information

17146.4k](/packages/juanparati-iso-codes)[josiasmontag/laravel-localization

Localization for Laravel framework

2336.2k](/packages/josiasmontag-laravel-localization)

PHPackages © 2026

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