PHPackages                             n02srt/laravel-auto-archive - 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. [Database &amp; ORM](/categories/database)
4. /
5. n02srt/laravel-auto-archive

ActiveLibrary[Database &amp; ORM](/categories/database)

n02srt/laravel-auto-archive
===========================

Auto-archive Eloquent models by moving old records into a dedicated archive database.

06PHP

Since Apr 25Pushed 1y ago1 watchersCompare

[ Source](https://github.com/N02SRT/laravel-auto-archive)[ Packagist](https://packagist.org/packages/n02srt/laravel-auto-archive)[ RSS](/packages/n02srt-laravel-auto-archive/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Auto Archive
====================

[](#laravel-auto-archive)

**`n02srt/laravel-auto-archive`** is a drop-in Laravel package that automates archiving of old Eloquent model data. It supports encrypted columns, separate archive databases, soft delete logic, queueing, dry-runs, and event notifications — all with easy setup and clean defaults.

---

🚀 Installation
--------------

[](#-installation)

```
composer require n02srt/laravel-auto-archive
```

Then run:

```
php artisan auto-archive:setup App\Models\Invoice --days=90
```

✔️ This publishes config, injects the trait, registers your model, builds migrations, and runs them.

---

✨ Features
----------

[](#-features)

### 🧠 Archive Methods

[](#-archive-methods)

This package supports three archiving strategies. You can define the method globally in `config/auto-archive.php`:

```
'method' => 'move' // options: 'move', 'flag', 'mirror'
```

#### 🔁 move (default)

[](#-move-default)

- Moves records to the archive database
- Deletes them from the primary database
- Honors `hard_delete` if set to true for physical deletion

#### 🏷️ flag

[](#️-flag)

- Sets an `archived_at` timestamp in the original table
- Keeps the data in place
- Useful for soft-style archiving without migrations

#### 🪞 mirror (NEW)

[](#-mirror-new)

- Copies matching records to the archive database
- Leaves the original data untouched
- Ideal for analytics, backups, or compliance snapshots

---

### 📆 Per-Model Retention

[](#-per-model-retention)

Override archive timing for specific models using:

```
protected static $archiveAfterDays = 90;
```

---

### 🧼 Selective Column Archiving

[](#-selective-column-archiving)

Archive only the fields you need:

```
protected $archiveColumns = ['id', 'amount', 'customer_id'];
```

---

### 🔐 Encrypted Columns

[](#-encrypted-columns)

Secure sensitive fields during archival:

```
protected $archiveEncryptedColumns = ['ssn', 'email'];
```

Encryption uses Laravel’s `Crypt` service.

---

### 💣 Hard Delete After Archive

[](#-hard-delete-after-archive)

When enabled, archived records are fully removed from the source database (not soft-deleted).

```
'hard_delete' => true
```

Use with caution in production!

---

### 🔁 Queue Support

[](#-queue-support)

Archive in the background with:

```
php artisan archive:models --queue
```

Supports Laravel Horizon and retry/backoff settings.

---

### 🧪 Dry-Run Preview

[](#-dry-run-preview)

Preview what would be archived or restored without making changes:

```
php artisan archive:models --dry-run
php artisan restore:archived App\Models\Invoice --dry-run
```

---

### 📋 Archive Logs (Optional)

[](#-archive-logs-optional)

Enable audit logging:

```
'logging' => ['enabled' => true]
```

Archived records are written to a central `archive_logs` table.

---

### 📣 Notification Hooks

[](#-notification-hooks)

Notify external systems when models are archived or restored:

```
AUTO_ARCHIVE_NOTIFY_EMAIL=admin@example.com
AUTO_ARCHIVE_SLACK_WEBHOOK=https://hooks.slack.com/services/...
AUTO_ARCHIVE_WEBHOOK_URL=https://yourapp.com/webhook
```

Available events:

- `ModelArchived`
- `ModelRestored`

---

### 🛡 Safety Features

[](#-safety-features)

- **Read-only mode:** Set `AUTO_ARCHIVE_READONLY=true` to block all operations
- **Soft delete bypass:** Use `bypass_soft_deletes => true` to include soft-deleted records
- **Max archive age:** Automatically purge stale archive data after N days

---

⚙️ Config File (Published to `config/auto-archive.php`)
-------------------------------------------------------

[](#️-config-file-published-to-configauto-archivephp)

```
'default_retention_days' => 30,
'method'                => 'move',
'archive_connection'    => 'archive',
'batch_size'            => 1000,
'pause_seconds'         => 1,
'max_archive_age'       => 365,
'bypass_soft_deletes'   => false,
'readonly'              => env('AUTO_ARCHIVE_READONLY', false),
'hard_delete'           => false,
'logging' => [
    'enabled' => env('AUTO_ARCHIVE_LOGGING_ENABLED', true),
],
'notifications' => [
    'slack' => env('AUTO_ARCHIVE_SLACK_WEBHOOK'),
    'email' => env('AUTO_ARCHIVE_NOTIFY_EMAIL'),
    'webhook' => env('AUTO_ARCHIVE_WEBHOOK_URL'),
],
'encryption' => [
    'enabled' => true,
    'key'     => env('AUTO_ARCHIVE_ENCRYPTION_KEY'),
],
'models' => [
    // App\Models\Invoice::class,
],
```

---

🧪 Artisan Command Summary
-------------------------

[](#-artisan-command-summary)

```
php artisan archive:models                  # Run archiving
php artisan archive:models --dry-run        # Preview without changes
php artisan archive:models --queue          # Queue archiving
php artisan restore:archived App\Model 42  # Restore single record
php artisan archive:cleanup                 # Delete expired archive records
```

---

🧬 Example Model
---------------

[](#-example-model)

```
use N02srt\AutoArchive\Traits\AutoArchiveable;

class Invoice extends Model
{
    use AutoArchiveable;

    protected static $archiveAfterDays = 90;
    protected $archiveColumns = ['id', 'amount', 'customer_id'];
    protected $archiveEncryptedColumns = ['amount'];

    public function scopeArchiveScope($query)
    {
        return $query->where('status', 'paid');
    }
}
```

---

📄 License
---------

[](#-license)

MIT © Steve Ash
Your database just got leaner. 🧹

---

⚠️ Disclaimer
-------------

[](#️-disclaimer)

This package includes functionality that can permanently **delete records** from your database.
If you enable features like `hard_delete`, records will be irreversibly removed from the primary database.

Please make sure you:

- Understand what each configuration setting does
- Test in staging or development environments first
- Keep backups of your data

> **I am not responsible for any data loss, misconfiguration, or unintended consequences from using this package. Use at your own risk.**

###  Health Score

16

—

LowBetter than 5% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity15

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/3256eb24f6e1dd1776a0fcfcc5294cff27d3a7dfc450acceb0f96a7310def8bb?d=identicon)[N02SRT](/maintainers/N02SRT)

---

Top Contributors

[![N02SRT](https://avatars.githubusercontent.com/u/14588565?v=4)](https://github.com/N02SRT "N02SRT (11 commits)")

### Embed Badge

![Health badge](/badges/n02srt-laravel-auto-archive/health.svg)

```
[![Health](https://phpackages.com/badges/n02srt-laravel-auto-archive/health.svg)](https://phpackages.com/packages/n02srt-laravel-auto-archive)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.4k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M546](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

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