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 class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
php
<?php final class RotatingFileLogger {
How a rotating file logger works in PHP
logging
file-rotation
io
Intermediate
9 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 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.