#laravel
#eloquent
#maintenance
Pruning Data in Laravel
Over time, applications accumulate records that serve no ongoing purpose — old logs, expired tokens, soft-deleted models, and stale queue jobs. Leaving these in your database slows queries, inflates storage costs, and makes backups larger than they need to be.
Laravel's Prunable and MassPrunable traits give you a clean, scheduled way to delete these records automatically, without writing custom artisan commands.
Setting Up the Prunable Trait
Add the Prunable trait to any model you want to automatically clean up. Define a prunable() method that returns a query scoping which records should be deleted. In this example, any Log record older than 30 days will be removed:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
class Log extends Model
{
use Prunable;
public function prunable()
{
return $this->where('created_at', '<', now()->subDays(30));
}
}
Add To Scheduler
Add the following line to the scheduler to run prunable daily.
<?php
use Illuminate\Support\Facades\Schedule;
Schedule::command('model:prune')->daily();