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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The Prunable trait lets a model define its own retention policy instead of scattering cleanup logic across schedulers.
- 2A prunable query should exclude records you explicitly want to keep, like ones flagged as retained.
- 3The pruning hook is the place to release external resources tied to a row, such as files, before deletion.
Related explainers
php
<?php namespace App\Http\Controllers;
Building a multi-step onboarding wizard in Laravel
session-state
validation
multi-step-forms
Intermediate
9 steps
php
<?php namespace App\Http;
HTTP content negotiation in PHP
http
content-negotiation
parsing
Intermediate
9 steps
php
<?php namespace App\Listeners;
Generating responsive images in a Laravel listener
queued jobs
event listeners
image processing
Intermediate
7 steps
php
final class InvoiceCalculator { private const SCALE = 4;
Precise money math with PHP's BCMath
bcmath
arbitrary precision
money
Intermediate
8 steps
php
<?php namespace App\Jobs;
Debouncing a Laravel shipping-rate job
queues
debouncing
atomic-locks
Advanced
9 steps
php
<?php namespace App\Models\Concerns;
Building soft deletes as an Eloquent trait in Laravel
traits
soft-delete
global-scope
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/auto-pruning-old-records-with-laravel-s-prunable-explained-php-36d6/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.