PHPackages                             nguyenhiepvan/laravel-model-cleanup - 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. nguyenhiepvan/laravel-model-cleanup

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

nguyenhiepvan/laravel-model-cleanup
===================================

This package deletes unneeded records in a database.

3.1.1(5y ago)05MITPHPPHP ^7.2

Since Mar 18Pushed 5y agoCompare

[ Source](https://github.com/nguyenhiepvan/laravel-model-cleanup)[ Packagist](https://packagist.org/packages/nguyenhiepvan/laravel-model-cleanup)[ Docs](https://github.com/spatie/laravel-model-cleanup)[ GitHub Sponsors](https://github.com/spatie)[ RSS](/packages/nguyenhiepvan-laravel-model-cleanup/feed)WikiDiscussions master Synced yesterday

READMEChangelog (2)Dependencies (10)Versions (27)Used By (0)

Clean up unneeded records
=========================

[](#clean-up-unneeded-records)

[![Latest Version on Packagist](https://camo.githubusercontent.com/68beb4ea596b49d072ecc9a5db5af65d0668e4207885148ec62ae758e26a8134/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7370617469652f6c61726176656c2d6d6f64656c2d636c65616e75702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-model-cleanup)[![Tests](https://github.com/spatie/laravel-model-cleanup/workflows/run-tests/badge.svg)](https://github.com/spatie/laravel-model-cleanup/workflows/run-tests/badge.svg)[![Psalm](https://github.com/spatie/laravel-model-cleanup/workflows/Psalm/badge.svg)](https://github.com/spatie/laravel-model-cleanup/workflows/Psalm/badge.svg)[![Total Downloads](https://camo.githubusercontent.com/d0f2a892f507e2d9c478b807da87aecd57bacf8a6afc4b5013c662956c03907c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7370617469652f6c61726176656c2d6d6f64656c2d636c65616e75702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/spatie/laravel-model-cleanup)[![MIT Licensed](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)

This package will clean up old records.

The models you wish to clean up should have a method `cleanUp` which returns the configuration how the model should be cleaned up. Here's an example where all records older than 5 days will be cleaned up.

```
use Illuminate\Database\Eloquent\Model;
use Spatie\ModelCleanup\CleanupConfig;
use Spatie\ModelCleanup\GetsCleanedUp;

class YourModel extends Model implements GetsCleanedUp
{
    ...

     public function cleanUp(CleanupConfig $config): void
     {
         $config->olderThanDays(5);
     }
}
```

After registering the model in the config file, running the `clean:models` artisan command will delete all records that have been created more than 5 days ago.

The package contains various other methods for specifying which records should be deleted.

Support us
----------

[](#support-us)

Learn how to create a package like this one, by watching our premium video course:

[![Laravel Package training](https://camo.githubusercontent.com/4c7f3720a29525e627f6004ee367e55def510e45d18e6bc974725812fa5cf257/68747470733a2f2f7370617469652e62652f6769746875622f7061636b6167652d747261696e696e672e6a7067)](https://laravelpackage.training)

We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).

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

[](#installation)

You can install the package via composer:

```
composer require spatie/laravel-model-cleanup
```

Next, you must publish the config file:

```
php artisan vendor:publish --provider="Spatie\ModelCleanup\ModelCleanupServiceProvider"
```

This is the content of the published config file `model-cleanup.php`.

```
return [

    /*
     * All models in this array that implement `Spatie\ModelCleanup\GetsCleanedUp`
     * will be cleaned.
     */
    'models' => [
        // App\Models\YourModel::class,
    ],
];
```

Optionally, you can schedule the `Spatie\ModelCleanup\Commands\CleanUpModelsCommand` to run at a frequency of which you want to clean up models. Here's an example where all models will be cleaned up every day at midnight.

```
// in app/Console/Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command(\Spatie\ModelCleanup\Commands\CleanUpModelsCommand::class)->daily();
}
```

Usage
-----

[](#usage)

All models that you want to clean up must implement the `GetsCleanedUp`-interface. In the required `cleanUp`-method you can specify which records are considered old and should be deleted.

Here's an example where all records older than 5 days will be cleaned up.

```
use Illuminate\Database\Eloquent\Model;
use Spatie\ModelCleanup\CleanupConfig;
use Spatie\ModelCleanup\GetsCleanedUp;

class YourModel extends Model implements GetsCleanedUp
{
    ...

     public function cleanUp(CleanupConfig $config): void
     {
        $config->olderThanDays(5);
     }
}
```

Next, you should register this model in the `models` key of the `model-cleanup` config file.

```
// in config/model-cleanup.php

return [
    'models' => [
        App\Models\YourModel::class,
    ],

    // ...
]
```

When running the console command `clean:models` all models older than 5 days will be deleted.

### Soft deleted models

[](#soft-deleted-models)

This package also supports cleaning up models that have soft deleting enabled. Models that use the `Illuminate\Database\Eloquent\SoftDeletes` trait and are considered old, will be permanently removed from your database instead of being marked as deleted.

### Available methods on `CleanupConfig`

[](#available-methods-on-cleanupconfig)

### `olderThanDays`

[](#olderthandays)

Using this method you can mark records that have a `created_at` value older than a given number of days as old.

Here's an example where all models older than 5 days are considered old.

```
 public function cleanUp(CleanupConfig $config): void
 {
    $config->olderThanDays(5);
 }
```

### `olderThan`

[](#olderthan)

The `olderThan` method accepts an instance of `Carbon`. All models with a `created_at` value before that instance, will be considered old.

Here's an example where all models older than a year are considered old.

```
 public function cleanUp(CleanupConfig $config): void
 {
    $config->olderThan(now()->subYear());
 }
```

### `useDateAttribute`

[](#usedateattribute)

When using `olderThanDays` and `olderThan` methods, the deletion query that is built up behind the scenes will use the `created_at` column. You can specify an alternative column, using the `useDateAttribute` method.

```
 public function cleanUp(CleanupConfig $config): void
 {
    $config
        ->olderThanDays(5)
        ->useDateAttribute('custom_date_column');
 }
```

### `scope`

[](#scope)

Using the `scope` method you can make the query that will delete old records more specific.

Assume that your model has a `status` attribute. Only records with a status `inactive` may be cleaned up. Here's an example where all records with an `inactive` status that are older than 5 days will be cleaned up.

```
 public function cleanUp(CleanupConfig $config): void
 {
    $config
       ->olderThanDays(5)
       ->scope(fn (Illuminate\Database\Eloquent\Builder $query) => $query->where('status', 'inactive'));
}
```

### `chunk`

[](#chunk)

By default, models get cleaned up by performing a single `delete` query. When you want to clean up a very large table, this single query could lock your table for a long time. It even might not be possible to get the lock in the first place.

To solve this, the package can delete records in chunks using the `chunk` method.

In this example, all records older than 5 days will be deleted in chucks of a 1000 records.

```
 public function cleanUp(CleanupConfig $config): void
 {
    $config
       ->olderThanDays(5)
       ->chunk(1000);
}
```

The package will stop deleting records when there are no more left that should be deleted.

If you need more fine-grained control over when to stop deleting, you can pass a closure as a second argument to `chunk`. Returning `false` in the closure will stop the deletion process.

In the example below, the deletion process will continue until all records older than 5 days are deleted or the record count of the model goes below 5000.

```
 public function cleanUp(CleanupConfig $config): void
 {
    $config
       ->olderThanDays(5)
       ->chunk(1000, fn() => YourModel::count() > 5000);
}
```

Events
------

[](#events)

After the model has been cleaned `Spatie\ModelCleanup\Events\ModelCleanedUp` will be fired even if there were no records deleted.

It has two public properties: `model`, which contains an instance of the model which was cleaned up. and `numberOfDeletedRecords`.

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Testing
-------

[](#testing)

```
composer test
```

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

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Postcardware
------------

[](#postcardware)

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).

Credits
-------

[](#credits)

- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity4

Limited adoption so far

Community18

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 69.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

Every ~64 days

Recently: every ~6 days

Total

26

Last Release

2093d ago

Major Versions

0.0.1 → 1.0.02016-03-18

v1.x-dev → 2.0.02017-09-01

2.5.0 → 3.0.02020-07-22

PHP version history (4 changes)0.0.1PHP ^7.0

2.0.3PHP ^7.1

3.0.0PHP ^7.4

3.1.1PHP ^7.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/5ee7ece29e66e7029d6b12d947a7d9714ae36346f21e92d767cfc797b86949d8?d=identicon)[nguyenhiepvan](/maintainers/nguyenhiepvan)

---

Top Contributors

[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (87 commits)")[![sebastiandedeyne](https://avatars.githubusercontent.com/u/1561079?v=4)](https://github.com/sebastiandedeyne "sebastiandedeyne (9 commits)")[![nguyenhiepvan](https://avatars.githubusercontent.com/u/33170716?v=4)](https://github.com/nguyenhiepvan "nguyenhiepvan (3 commits)")[![jochensengier](https://avatars.githubusercontent.com/u/10118729?v=4)](https://github.com/jochensengier "jochensengier (3 commits)")[![brendt](https://avatars.githubusercontent.com/u/6905297?v=4)](https://github.com/brendt "brendt (3 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (2 commits)")[![devinfd](https://avatars.githubusercontent.com/u/468399?v=4)](https://github.com/devinfd "devinfd (1 commits)")[![dmason30](https://avatars.githubusercontent.com/u/20278756?v=4)](https://github.com/dmason30 "dmason30 (1 commits)")[![drfraker](https://avatars.githubusercontent.com/u/1279323?v=4)](https://github.com/drfraker "drfraker (1 commits)")[![dwightwatson](https://avatars.githubusercontent.com/u/1100408?v=4)](https://github.com/dwightwatson "dwightwatson (1 commits)")[![francislavoie](https://avatars.githubusercontent.com/u/2111701?v=4)](https://github.com/francislavoie "francislavoie (1 commits)")[![carusogabriel](https://avatars.githubusercontent.com/u/16328050?v=4)](https://github.com/carusogabriel "carusogabriel (1 commits)")[![bolechen](https://avatars.githubusercontent.com/u/195015?v=4)](https://github.com/bolechen "bolechen (1 commits)")[![lloy0076](https://avatars.githubusercontent.com/u/1174532?v=4)](https://github.com/lloy0076 "lloy0076 (1 commits)")[![michelecurletta](https://avatars.githubusercontent.com/u/65455871?v=4)](https://github.com/michelecurletta "michelecurletta (1 commits)")[![BackEndTea](https://avatars.githubusercontent.com/u/14289961?v=4)](https://github.com/BackEndTea "BackEndTea (1 commits)")[![Omranic](https://avatars.githubusercontent.com/u/406705?v=4)](https://github.com/Omranic "Omranic (1 commits)")[![pktharindu](https://avatars.githubusercontent.com/u/23132672?v=4)](https://github.com/pktharindu "pktharindu (1 commits)")[![akoepcke](https://avatars.githubusercontent.com/u/5311185?v=4)](https://github.com/akoepcke "akoepcke (1 commits)")[![skalero01](https://avatars.githubusercontent.com/u/2976641?v=4)](https://github.com/skalero01 "skalero01 (1 commits)")

---

Tags

spatielaravel-model-cleanup

###  Code Quality

TestsPest

Static AnalysisPsalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/nguyenhiepvan-laravel-model-cleanup/health.svg)

```
[![Health](https://phpackages.com/badges/nguyenhiepvan-laravel-model-cleanup/health.svg)](https://phpackages.com/packages/nguyenhiepvan-laravel-model-cleanup)
```

###  Alternatives

[spatie/laravel-backup

A Laravel package to backup your application

6.0k21.8M191](/packages/spatie-laravel-backup)[spatie/laravel-medialibrary

Associate files with Eloquent models

6.1k37.7M472](/packages/spatie-laravel-medialibrary)[spatie/laravel-sluggable

Generate slugs when saving Eloquent models

1.6k11.5M223](/packages/spatie-laravel-sluggable)[spatie/laravel-translatable

A trait to make an Eloquent model hold translations

2.4k23.0M413](/packages/spatie-laravel-translatable)[spatie/laravel-db-snapshots

Quickly dump and load databases

1.2k2.8M20](/packages/spatie-laravel-db-snapshots)[spatie/laravel-schemaless-attributes

Add schemaless attributes to Eloquent models

1.1k8.7M62](/packages/spatie-laravel-schemaless-attributes)

PHPackages © 2026

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