Skip to main content
Quick Tip

Periodic cleaning of models from obsolete records

To periodically clean models of obsolete records. With this trait, Laravel will do this automatically, only you need to adjust the frequency of the model:prune command in the Kernel class.

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
class Flight extends Model
{
use Prunable;
/**
* Get the prunable model query.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function prunable()
{
return static::where('created_at', '<=', now()->subMonth());
}
}

Also, in the pruning method, you can set the actions that must be performed before deleting the model:

protected function pruning()
{
// Removing additional resources,
// associated with the model. For example, files.
 
Storage::disk('s3')->delete($this->filename);
}

Tip given by @PascalBaljet

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

Filament 4 From Scratch

28 lessons
2 h 25 min

Claude Code for Laravel Projects: Crash Course

8 lessons
48 min

Laravel HTTP Client and 3rd-Party APIs

7 lessons
50 min

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.