php 37 lines · 5 steps

Auto-pruning old records with Laravel's Prunable

An Eloquent model that periodically deletes stale audit logs and cleans up their archived files as it goes.

Explained by highlit
1<?php
2 
3namespace App\Models;
4 
5use Illuminate\Database\Eloquent\Builder;
6use Illuminate\Database\Eloquent\Model;
7use Illuminate\Database\Eloquent\Prunable;
8use Illuminate\Support\Facades\Storage;
9 
10class AuditLog extends Model
11{
12 use Prunable;
13 
14 protected $fillable = [
15 'event',
16 'ip_address',
17 'payload',
18 'archive_path',
19 ];
20 
21 protected $casts = [
22 'payload' => 'array',
23 ];
24 
25 public function prunable(): Builder
26 {
27 return static::where('created_at', '<=', now()->subMonths(3))
28 ->whereNull('retained_at');
29 }
30 
31 protected function pruning(): void
32 {
33 if ($this->archive_path && Storage::disk('audits')->exists($this->archive_path)) {
34 Storage::disk('audits')->delete($this->archive_path);
35 }
36 }
37}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The Prunable trait lets a model define its own retention policy instead of scattering cleanup logic across schedulers.
  2. 2A prunable query should exclude records you explicitly want to keep, like ones flagged as retained.
  3. 3The pruning hook is the place to release external resources tied to a row, such as files, before deletion.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Auto-pruning old records with Laravel's Prunable — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code