Automate Old Record Deletion with Prunable
Managing outdated data? Here's a real-world example of how I automated deleting old "Activity" records in my Laravel project using the Prunable trait. Let's dive in! 🚀
📝 Scenario: Cleaning Up Old Activities
In my application, I have an Activity model that tracks various user actions. Over time, this table gets bloated with unnecessary records. To keep things optimized, I decided to automatically delete activities older than 6 months.
💡 Here’s How I Did It
1️⃣ Set Up Prunable in the Activity Model
First, I added Laravel's Prunable trait to the Activity model:
Recommended by LinkedIn
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
use Carbon\Carbon;
class Activity extends Model
{
use Prunable;
/**
* Get the prunable query.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function prunable()
{
// Select activities older than 6 months
return static::where('created_at', '<', now()->subMonths(6));
}
/**
* Handle the pruning process for each prunable model.
*/
protected function pruning()
{
\Log::info('Pruning Activity ID: ' . $this->id . ', Details: ' . $this->details);
}
/**
* Handle post-pruning actions.
*/
protected function pruned()
{
\Log::info('Activity ID ' . $this->id . ' successfully deleted!');
}
}
2️⃣ Schedule Automatic Deletion
To automate this, I used Laravel's task scheduler. Here's how I scheduled the pruning command:
// For laravel 11 "routes/console.php"
use Illuminate\Support\Facades\Schedule;
Schedule::command('model:prune')->daily();
// For Laravel 10 and Earlier Versions "Kernel.php"
protected function schedule(Schedule $schedule)
{
$schedule->command('model:prune')->daily();
}
🌟 Why This Approach Rocks