Laravel Cleanup Data
Data-retention and cleanup framework for Laravel
Old logs, exports, and temp files pile up, and ad-hoc prune scripts end up scattered across the app. Define retention rules once, preview with a dry run, schedule them, and get hooks and logs around every run.
Requirements
- PHP 8.4+
- Laravel 12–13
Install with Composer
composer require t-labs-co/laravel-cleanup-dataRetention logic shouldn’t live in scattered cron jobs. Laravel Cleanup Data lets you define retention rules once, then delete or anonymize old records on a schedule. Every run can be previewed with a dry run, capped by safety limits, and recorded in an audit log. It covers Eloquent models, files, exports, or anything else through custom cleaners.
Why not Prunable?
Laravel’s Prunable trait and model:prune are great for simple cases, and if all you do is delete old rows from a few models, use them. This package is for when retention becomes a policy rather than a one-off query.
| Prunable / model:prune | Laravel Cleanup Data | |
|---|---|---|
| Delete old model rows | ✅ YES | ✅ YES |
| Dry run | ✅ --pretend |
✅ --dry-run / ->dryRun() |
| Where rules live | On each model | Central registry + fluent API |
| Anonymize instead of delete | Custom code in pruning() | Built-in strategies (hash, mask, null, fixed) |
| Run anonymization only once | Manual | anonymized_at marker |
| Abort on mass-delete | Manual | max_affected cap |
| Files, exports, non-model data | Separate commands | Custom cleaners with tags |
| Run summaries | Manual | Audit log with counts and samples |
| Extra dependency | None | One package |
Choose Prunable if you only need to delete old rows from a few models. Choose this package if you want retention as a policy: dry runs, anonymization, safety caps, audit logs, and custom cleaners for files and exports.
Get started in minutes
Follow these steps to install the package, define your first cleanup rule, and verify it works.
1. Install the package
composer require t-labs-co/laravel-cleanup-data
This adds the package to your composer.json and installs all dependencies.
2. Publish the configuration file
php artisan vendor:publish --tag=laravel-cleanup-data-config
This creates config/laravel-cleanup-data.php where you can define cleaners, retention rules, and scheduling settings.
3. (Optional) Publish migrations for anonymization
If you plan to use idempotent anonymization for GDPR compliance:
php artisan vendor:publish --tag=laravel-cleanup-data-migrations
php artisan migrate
This adds the anonymized_at marker column to your tables, ensuring records are only anonymized once.
4. Define a cleanup rule
Use the fluent Cleaner facade for quick, ad-hoc cleanup:
use TLabsCo\LaravelCleanupData\Facades\Cleaner;
use App\Models\ActivityLog;
// Preview what would be deleted without touching data
$preview = Cleaner::model(ActivityLog::class)
->days(30)
->dryRun();
// Execute the cleanup
$result = Cleaner::model(ActivityLog::class)
->days(30)
->clean();
The dry-run mode shows you exactly which records will be affected before you delete them.
5. Run cleanup operations
# Run all enabled cleaners
php artisan cleanup:run
# Preview cleanup in dry-run mode
php artisan cleanup:run --dry-run
# List all registered cleaners
php artisan cleanup:list
The list command shows all registered cleaners, their tags, and whether they’re enabled.
6. Schedule recurring cleanup
Enable automatic scheduling in your environment configuration:
DATA_CLEANUP_SCHEDULE_ENABLED=true
DATA_CLEANUP_SCHEDULE_EXPRESSION="0 2 * * *"
This runs all enabled cleaners daily at 2 AM. For the complete configuration options, see the Configuration Reference on GitHub.
Features
GDPR-ready data retention
Not legal advice. The following describes technical building blocks the package provides. Consult legal counsel for GDPR compliance requirements.
Enforce data minimization by automatically pruning or anonymizing data that exceeds retention periods. The package provides building blocks for key GDPR requirements:
- Data Minimization (Art. 5) — Retention rules with
OlderThanandRetainUntil - Right to Erasure (Art. 17) — Delete and force-delete actions
- Pseudonymization (Art. 4) — Hashed emails, masked values, nullification
Data anonymization
Pseudonymize personal data while preserving data structure for analytics:
use TLabsCo\LaravelCleanupData\Facades\Cleaner;
use TLabsCo\LaravelCleanupData\Core\Retention\Strategy;
use App\Models\User;
$result = Cleaner::model(User::class)
->olderThan(years: 1)
->anonymize([
'email' => Strategy::hashedEmail(),
'phone' => Strategy::mask(keepLast: 4),
'name' => Strategy::fixed('Anonymized User'),
])
->clean();
Built-in strategies include hashed emails, masked values, nullification, fixed replacements, and custom closures.
Safety limits
Hard caps per run prevent accidental mass operations. If matched rows exceed max_affected, the operation aborts before any changes are written:
$result = ModelPruner::for(User::class)
->olderThan(years: 2)
->action(Action::delete())
->maxAffected(5_000)
->clean();
Dry-run mode
Always test cleanup scopes before execution. Dry-run mode returns the same result structure as a real run but doesn’t modify any data.
Rule-based retention engine
Compose declarative retention rules with any cleanup action — no boilerplate query code required:
use TLabsCo\LaravelCleanupData\Core\Services\ModelPruner;
use TLabsCo\LaravelCleanupData\Core\Retention\Action;
$result = ModelPruner::for(User::class)
->olderThan(years: 2)
->where('status', 'inactive')
->except(fn ($q) => $q->where('legal_hold', true))
->action(Action::delete())
->clean();
Custom cleaners
Extend BaseCleaner to create custom cleanup logic for storage files, exports, or any other data:
namespace App\Cleaners;
use TLabsCo\LaravelCleanupData\Core\Cleaners\BaseCleaner;
use TLabsCo\LaravelCleanupData\Core\ValueObject\CleanupResult;
class TempExportCleaner extends BaseCleaner
{
protected array $tags = ['storage', 'exports'];
public function getName(): string
{
return 'Temp Export Cleaner';
}
public function cleanup(bool $dryRun = false): CleanupResult
{
// Custom cleanup logic...
return CleanupResult::success(
cleaner: $this->getName(),
processed: 15,
deleted: $dryRun ? 0 : 15,
);
}
}
Configuration reference
Environment variables
| Variable | Default | Description |
|---|---|---|
DATA_CLEANUP_ENABLED |
true |
Master switch for all cleanup operations |
DATA_CLEANUP_RETENTION_MAX_AFFECTED |
10000 |
Safety limit: max rows per run |
DATA_CLEANUP_RETENTION_CHUNK_SIZE |
500 |
Batch chunk size for memory efficiency |
DATA_CLEANUP_SCHEDULE_ENABLED |
false |
Enable automatic cron scheduling |
DATA_CLEANUP_SCHEDULE_EXPRESSION |
0 2 * * * |
Cron expression (default: 2 AM daily) |
DATA_CLEANUP_LOGGING_ENABLED |
true |
Enable detailed cleanup logging |
Artisan commands
| Command | Description |
|---|---|
php artisan cleanup:run |
Run all enabled cleaners |
php artisan cleanup:run --dry-run |
Preview cleanup without executing |
php artisan cleanup:run --tag=storage |
Run cleaners with a specific tag |
php artisan cleanup:list |
List all registered cleaners |
Safety guarantees
- Idempotent anonymization — Records with
anonymized_atset are skipped on subsequent runs - Safety limits — Operations abort before any changes if matched rows exceed
max_affected - Dry-run preview — Always test cleanup scopes before execution
- Audit logging — All operations are logged with matched counts, changed counts, and samples
For complete documentation, see the README on GitHub.
Why I built it
After maintaining dozens of Laravel applications, I kept seeing the same problem: data-retention rules scattered across Artisan commands, cron scripts, and ad-hoc database queries. I built Laravel Cleanup Data to bring those rules into one testable, reusable workflow. Define what should be retained, deleted, or anonymized; preview changes before applying them; and enforce safety limits with logging around each run. The goal is simple: make routine data cleanup easier to maintain, safer to execute, and easier to audit as an application grows.
Hire me for Laravel data-retention work
Need a package tailored to your application? From recurring Laravel maintenance tasks to reusable components, I can help design, build, and review production-ready solutions.
Discuss your project
Support this package