PHPackages                             plin-code/laravel-istat-geography - 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. plin-code/laravel-istat-geography

ActiveLibrary

plin-code/laravel-istat-geography
=================================

Laravel package for importing and managing Italian geography data from ISTAT

v1.2.0(2mo ago)94.9k↓15.8%MITPHPPHP ^8.3CI passing

Since Aug 7Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/plin-code/laravel-istat-geography)[ Packagist](https://packagist.org/packages/plin-code/laravel-istat-geography)[ Docs](https://github.com/plin-code/laravel-istat-geography)[ GitHub Sponsors](https://github.com/PlinCode)[ RSS](/packages/plin-code-laravel-istat-geography/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (6)Dependencies (28)Versions (8)Used By (0)

Laravel ISTAT Geography
=======================

[](#laravel-istat-geography)

[![Latest Version on Packagist](https://camo.githubusercontent.com/fe36825d74015754b374c46d063d0473f637863793f3a9b70786495db4975a39/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f706c696e2d636f64652f6c61726176656c2d69737461742d67656f6772617068792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/plin-code/laravel-istat-geography)[![GitHub Tests Action Status](https://camo.githubusercontent.com/9bee38ace35445b98c4fd9f818c6d1809e9352f75fcc63bed04c6d247d779fdc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f706c696e2d636f64652f6c61726176656c2d69737461742d67656f6772617068792f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473)](https://github.com/plin-code/laravel-istat-geography/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/392fe6fc3f25810f87c53a1161d5b220761a930cddf7ec5876c8e4d61d94d2dd/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f706c696e2d636f64652f6c61726176656c2d69737461742d67656f6772617068792f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65)](https://github.com/plin-code/laravel-istat-geography/actions?query=workflow%3A%22Check+%26+fix+styling%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/b53e2460afa0aa8586fb70c7a99296b983ceb80526420ba34575bb7a5c0953a6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f706c696e2d636f64652f6c61726176656c2d69737461742d67656f6772617068792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/plin-code/laravel-istat-geography)

 [![Laravel ISTAT Geography](art/laravel-istat-geography.png)](art/laravel-istat-geography.png)

A Laravel package for importing and managing Italian geographical data from ISTAT.

Features
--------

[](#features)

- 🇮🇹 Import Italian regions, provinces, and municipalities from ISTAT
- 📮 Import Italian postal codes (CAP) with support for multi-CAP municipalities
- 🔄 Incremental updates: add new records, update changes, soft-delete removed ones
- 📊 Daily CSV caching to avoid unnecessary requests
- 🔗 Eloquent models with hierarchical relationships
- ⚡ Artisan commands for easy data import and synchronization
- 🔧 Fully configurable via configuration file
- 🆔 UUID primary keys and soft deletes support
- 🧪 Comprehensive test suite with mocked HTTP requests

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

[](#requirements)

- PHP 8.3+
- Laravel 11.0+ or 12.0+
- league/csv 9.0+
- guzzlehttp/guzzle 7.0+

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

[](#installation)

```
composer require plin-code/laravel-istat-geography
```

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

[](#quick-start)

1. **Install the package:**

```
composer require plin-code/laravel-istat-geography
```

2. **Publish the configuration:**

```
php artisan vendor:publish --provider="PlinCode\IstatGeography\IstatGeographyServiceProvider"
```

3. **Run migrations:**

```
php artisan migrate
```

4. **Import the data:**

```
php artisan geography:import
```

That's it! You now have all Italian geographical data in your database.

Commands
--------

[](#commands)

### `geography:import`

[](#geographyimport)

Performs a full import of all geographical data from ISTAT. Use this for the initial data load.

```
php artisan geography:import
```

#### Options

[](#options)

OptionDescription`--cap`Also import postal codes (CAP) after ISTAT data`--cap-only`Import only postal codes, skip ISTAT data (requires existing municipalities)`--cap-file=`Use a local JSON file for CAP data instead of downloading#### Examples

[](#examples)

```
# Import ISTAT data only
php artisan geography:import

# Import ISTAT data + CAP (using local file - recommended)
php artisan geography:import --cap --cap-file=cap-dataset.json

# Update only CAP on existing municipalities
php artisan geography:import --cap-only --cap-file=cap-dataset.json
```

> **Note:** The remote GeoJSON with geometries is ~464MB. Using `--cap-file` with a preprocessed JSON file (~3MB) is recommended for better performance.

### `geography:download-cap`

[](#geographydownload-cap)

Downloads CAP GeoJSON data and saves it locally for offline import. Useful when you want to download once and import multiple times.

```
# Download from default URL (config/env)
php artisan geography:download-cap

# Download from custom URL
php artisan geography:download-cap --url=https://example.com/cap.json

# Specify output path
php artisan geography:download-cap --output=storage/app/my-cap.json
```

After downloading, import with:

```
php artisan geography:import --cap --cap-file=storage/app/cap-dataset.json
```

### `geography:update`

[](#geographyupdate)

Incrementally synchronizes your database with the latest ISTAT data. It compares the current ISTAT CSV against your existing records and applies only the differences: new records are added, changed records are updated, and records no longer present in ISTAT are soft-deleted.

```
php artisan geography:update
```

#### Options

[](#options-1)

OptionDescription`--dry-run`Simulate the update without making any database changes. Shows what would be added, modified, or deleted.`--force`Continue execution even if non-critical errors occur (errors are logged as warnings).#### Verbosity Levels

[](#verbosity-levels)

FlagOutput*(none)*Final summary only (e.g. `3 added, 1 modified, 0 deleted`)`-v`Download progress, list of new/modified/suppressed records, progress bar`-vv`Field-level change details (e.g. `name: Old Name → New Name`)`-vvv`Debug output with timing information for each operation#### Examples

[](#examples-1)

```
# Preview changes without applying them
php artisan geography:update --dry-run

# Run with verbose output
php artisan geography:update -v

# Run with full debug output
php artisan geography:update -vvv

# Force continue on non-critical errors
php artisan geography:update --force
```

All database operations are wrapped in a transaction. If any error occurs (and `--force` is not set), all changes are automatically rolled back.

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

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --provider="PlinCode\IstatGeography\IstatGeographyServiceProvider"
```

The `config/istat-geography.php` file allows you to customize:

- **Table names**: Customize the database table names
- **Model classes**: Use your own model classes by extending the base ones
- **CSV URL**: Change the ISTAT data source URL (also via `ISTAT_CSV_URL` env)
- **CAP GeoJSON URL**: Change the CAP data source URL (also via `CAP_GEOJSON_URL` env)
- **Temporary file name**: Customize the cache file name

### Example Configuration

[](#example-configuration)

```
return [
    'tables' => [
        'regions' => 'my_regions',
        'provinces' => 'my_provinces',
        'municipalities' => 'my_municipalities',
    ],
    'models' => [
        'region' => \App\Models\Region::class,
        'province' => \App\Models\Province::class,
        'municipality' => \App\Models\Municipality::class,
    ],
    'import' => [
        'csv_url' => 'https://custom-url.com/data.csv',
        'temp_filename' => 'my_istat_data.csv',
    ],
];
```

Models
------

[](#models)

The package provides three Eloquent models:

### Region

[](#region)

```
use PlinCode\IstatGeography\Models\Geography\Region;

$region = Region::where('name', 'Piemonte')->first();
$provinces = $region->provinces;
```

### Province

[](#province)

```
use PlinCode\IstatGeography\Models\Geography\Province;

$province = Province::where('code', 'TO')->first();
$municipalities = $province->municipalities;
$region = $province->region;
```

### Municipality

[](#municipality)

```
use PlinCode\IstatGeography\Models\Geography\Municipality;

$municipality = Municipality::where('name', 'Torino')->first();
$province = $municipality->province;
```

### ISTAT Fields

[](#istat-fields)

Each model exposes a static `istatFields()` method that returns the list of fields managed by ISTAT data. These are the fields that the `geography:update` command is allowed to overwrite. Any additional fields you add to your extended models will not be touched during updates.

```
Region::istatFields();       // ['name', 'istat_code']
Province::istatFields();     // ['name', 'code', 'istat_code', 'region_id']
Municipality::istatFields(); // ['name', 'istat_code', 'province_id', 'bel_code']
Municipality::capFields();   // ['postal_code', 'postal_codes']
```

### Extending Models

[](#extending-models)

If you want to use the package models in your main project, you can extend them:

```
// app/Models/Region.php
namespace App\Models;

use PlinCode\IstatGeography\Models\Geography\Region as BaseRegion;

class Region extends BaseRegion
{
    // Add your project-specific logic here
    public function customMethod()
    {
        return $this->provinces()->count();
    }
}
```

```
// app/Models/Province.php
namespace App\Models;

use PlinCode\IstatGeography\Models\Geography\Province as BaseProvince;

class Province extends BaseProvince
{
    // Add your project-specific logic here
}
```

```
// app/Models/Municipality.php
namespace App\Models;

use PlinCode\IstatGeography\Models\Geography\Municipality as BaseMunicipality;

class Municipality extends BaseMunicipality
{
    // Add your project-specific logic here
}
```

Remember to update the `models` section in the configuration file to point to your custom classes.

Database Structure
------------------

[](#database-structure)

### Regions

[](#regions)

- `id` (UUID, primary key)
- `name` (string)
- `istat_code` (string, unique)
- `created_at`, `updated_at`, `deleted_at`

### Provinces

[](#provinces)

- `id` (UUID, primary key)
- `region_id` (UUID, foreign key)
- `name` (string)
- `code` (string, unique)
- `istat_code` (string, unique)
- `created_at`, `updated_at`, `deleted_at`

### Municipalities

[](#municipalities)

- `id` (UUID, primary key)
- `province_id` (UUID, foreign key)
- `name` (string)
- `istat_code` (string, unique)
- `bel_code` (string, nullable) - Cadastral/Belfiore code for CAP matching
- `postal_code` (string, nullable) - Primary postal code (CAP)
- `postal_codes` (string, nullable) - Range of postal codes for large municipalities (e.g., "00118-00199")
- `created_at`, `updated_at`, `deleted_at`

Relationships
-------------

[](#relationships)

- `Region` → `hasMany` → `Province`
- `Province` → `belongsTo` → `Region`
- `Province` → `hasMany` → `Municipality`
- `Municipality` → `belongsTo` → `Province`

Replacing Existing Command
--------------------------

[](#replacing-existing-command)

If you already have a `geography:import` command in your project, you can replace it with the package's command:

```
// In app/Console/Kernel.php or in your existing command
Artisan::command('geography:import', function () {
    $this->info('Starting geographical data import...');

    try {
        $count = \PlinCode\IstatGeography\Facades\IstatGeography::import();
        $this->info("Import completed successfully! Imported {$count} municipalities.");
    } catch (\Exception $e) {
        $this->error('Error during import: ' . $e->getMessage());
    }
})->purpose('Import regions, provinces and municipalities from ISTAT');
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

The package includes:

- ✅ Unit tests for models and relationships
- ✅ Feature tests for the import service
- ✅ Feature tests for the update command and services
- ✅ Mocked HTTP requests (no external dependencies)
- ✅ PHPStan static analysis
- ✅ Pest PHP testing framework

### Test Coverage

[](#test-coverage)

- Models and their relationships
- Import service with CSV processing
- Compare service for detecting changes
- Update service for applying changes
- Artisan command functionality (import and update)
- Configuration handling

Data Sources
------------

[](#data-sources)

### ISTAT Data

[](#istat-data)

Geographic data (regions, provinces, municipalities) is sourced from [ISTAT](https://www.istat.it/) (Italian National Institute of Statistics), the official Italian government statistics agency.

### Postal Codes (CAP)

[](#postal-codes-cap)

Postal code data is sourced from [Zornade Data Downloads](https://zornade.com/data-downloads/).

A huge thanks to [Zornade](https://github.com/zornade) for their incredible work in making Italian public data freely available. Their dedication to open data helps developers build better applications for Italian users.

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

[](#contributing)

1. Fork the project
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance89

Actively maintained with recent releases

Popularity29

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 80.5% 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 ~74 days

Total

4

Last Release

60d ago

PHP version history (2 changes)v1.0.0PHP ^8.4

v1.0.1PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/7653cedfb706bdbaceab17cb57fa55d5e2744faeb722cfc1e2af8c3fd88f13ef?d=identicon)[danielebarbaro](/maintainers/danielebarbaro)

---

Top Contributors

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

---

Tags

geographyhacktoberfesthacktoberfest2025istatlaravelprovinceregionlaravelcountriesgeographyitalyregionsprovincesmunicipalitiesistatPlinCode

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/plin-code-laravel-istat-geography/health.svg)

```
[![Health](https://phpackages.com/badges/plin-code-laravel-istat-geography/health.svg)](https://phpackages.com/packages/plin-code-laravel-istat-geography)
```

###  Alternatives

[spatie/laravel-health

Monitor the health of a Laravel application

86910.0M83](/packages/spatie-laravel-health)[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)[sunchayn/nimbus

A Laravel package providing an in-browser API client with automatic schema generation, live validation, and built-in authentication with a touch of Laravel-tailored magic for effortless API testing.

29428.0k](/packages/sunchayn-nimbus)[muhammadhuzaifa/telescope-guzzle-watcher

Telescope Guzzle Watcher provide a custom watcher for intercepting http requests made via guzzlehttp/guzzle php library. The package uses the on\_stats request option for extracting the request/response data. The watcher intercept and log the request into the Laravel Telescope HTTP Client Watcher.

98239.8k1](/packages/muhammadhuzaifa-telescope-guzzle-watcher)[spatie/laravel-mailcoach-sdk

An SDK to easily work with the Mailcoach API in Laravel apps

41290.2k1](/packages/spatie-laravel-mailcoach-sdk)[ralphjsmit/laravel-helpers

A package containing handy helpers for your Laravel-application.

13704.6k2](/packages/ralphjsmit-laravel-helpers)

PHPackages © 2026

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