Intermediate LevelLaravel
How does the Pruning trait handle automatic background model deletion?
❓ Interview Prompt: Explain Prunable vs MassPrunable traits, prunable() query builder method, and php artisan model:prune.
Laravel provides Prunable and MassPrunable traits to automatically clean up stale database records (old logs, expired tokens, abandoned carts):
How it Works:
1
Add 'use Prunable;' trait to Eloquent model.
2
Define 'prunable()' returning a query builder ('Model::where("created_at", "<", now()->subDays(30))').
3
Scheduled command 'php artisan model:prune' deletes stale records automatically!
Code Implementation Example
php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentPrunable;
use IlluminateDatabaseEloquentBuilder;
class AuditLog extends Model
{
use Prunable;
public function prunable(): Builder {
return static::where('created_at', '<', now()->subDays(90));
}
}💡Eloquent Model using Prunable trait to auto-delete logs older than 90 days.
🎯 Interview Key Takeaway
Use the Prunable trait and php artisan model:prune to automatically clean up stale database records.
#Prunable#Model Pruning#Maintenance#Intermediate
Back to all Laravel Questions→