In this episode, we dive straight into how you can make your models prunable in Laravel. It's surprisingly easy! We start by including the prunable trait in our model, which is an opt-in feature—so you don't need to worry about any automatic behavior unless you specifically add it.
We then define a prunable
method on the model, which simply returns a query builder that determines which records should be eligible for pruning. Typically, you'd use a condition like checking if the created_at
date is older than a certain threshold (a week, a month, etc.).
Once that's set up, we run the php artisan model:prune
command. This goes through your models, checks if they're prunable, and starts deleting records in batches based on the condition you defined. You'll see a noticeable difference in your database after this runs!
We also look at some helpful options you can pass to the command, like including or excluding certain models, adjusting the chunk size, and even running in "pretend" mode for a dry run to see what would be deleted. Towards the end, we mention that we'll cover scheduling these prune operations later on in the course.
So, with just a couple of changes, you can keep your database clean and tidy. Easy, right?