Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Model Cleanup Laravel Package

spatie/laravel-model-cleanup

Deprecated: use Laravel’s built-in Prunable. Spatie’s laravel-model-cleanup deletes unneeded Eloquent records via a cleanUp() configuration per model, and an artisan command to prune records older than a given age or matching custom rules.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/laravel-model-cleanup
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\ModelCleanup\ModelCleanupServiceProvider"
    
  2. Configure Models: Edit config/model-cleanup.php to register your models under the models key:

    'models' => [
        \App\Models\YourModel::class,
    ],
    
  3. Define Cleanup Logic: Implement the GetsCleanedUp interface and cleanUp() method in your model:

    use Spatie\ModelCleanup\GetsCleanedUp;
    use Spatie\ModelCleanup\CleanupConfig;
    
    class YourModel extends Model implements GetsCleanedUp
    {
        public function cleanUp(CleanupConfig $config): void
        {
            $config->olderThanDays(5); // Example: Delete records older than 5 days
        }
    }
    
  4. Run Cleanup: Execute the Artisan command:

    php artisan cleanup:models
    

First Use Case

Use this package to automate cleanup of stale records (e.g., logs, temporary data, or expired entries). For example, delete old FailedJob records or Sessions after 30 days.


Implementation Patterns

Core Workflows

  1. Basic Cleanup: Define cleanup rules in cleanUp() using CleanupConfig:

    $config->olderThanDays(7); // Delete records older than 7 days
    $config->olderThanHours(24); // Delete records older than 24 hours
    
  2. Conditional Cleanup: Use closures to filter records dynamically:

    $config->where(function ($query) {
        $query->where('status', 'archived');
    })->olderThanDays(30);
    
  3. Batch Processing: Process cleanup in chunks to avoid locking tables:

    $config->chunk(100); // Process 100 records at a time
    
  4. Scheduling: Add a scheduled task in app/Console/Kernel.php:

    $schedule->command('cleanup:models')->daily();
    

Integration Tips

  • Logging: Wrap the cleanup command in a job and log results:
    public function handle()
    {
        $deleted = Artisan::call('cleanup:models');
        Log::info("Deleted {$deleted} records via cleanup:models");
    }
    
  • Testing: Mock the cleanup logic in tests:
    $model = new YourModel();
    $config = Mockery::mock(CleanupConfig::class);
    $model->cleanUp($config);
    $config->shouldHaveReceived('olderThanDays', [5]);
    
  • Soft Deletes: Combine with SoftDeletes for safer cleanup:
    $config->olderThanDays(30)->softDelete();
    

Gotchas and Tips

Pitfalls

  1. No Maintenance: The package is archived—use Laravel’s built-in prunable models instead (recommended for new projects).

    use Illuminate\Database\Eloquent\SoftDeletes;
    use Illuminate\Contracts\Prunable;
    
    class YourModel extends Model implements Prunable
    {
        use SoftDeletes;
    
        public static function prune()
        {
            static::where('created_at', '<=', now()->subDays(5))->delete();
        }
    }
    
  2. Config Registration: Forgetting to register models in config/model-cleanup.php will skip their cleanup.

  3. Performance: Large tables may cause timeouts. Use chunk() or run during off-peak hours.

  4. Transactions: Cleanup runs without transactions by default. For critical data, wrap in a transaction:

    DB::transaction(function () {
        Artisan::call('cleanup:models');
    });
    

Debugging

  • Dry Runs: Add --dry-run to the command to preview deletions:
    php artisan cleanup:models --dry-run
    
  • Logging: Enable debug mode in config/model-cleanup.php:
    'debug' => env('APP_DEBUG', false),
    
  • Query Inspection: Use Laravel Debugbar to inspect generated queries.

Extension Points

  1. Custom Cleanup Logic: Extend CleanupConfig for reusable rules:

    $config->custom(function ($query) {
        $query->where('is_active', false)->whereNull('deleted_at');
    });
    
  2. Event Listeners: Trigger events before/after cleanup:

    // In EventServiceProvider
    ModelCleanupStarting::class => function ($event) {
        Log::info('Starting cleanup for ' . $event->model);
    },
    
  3. Dynamic Config: Load cleanup rules from a database or cache for flexibility.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport