Pruning Laravel Models

In the latest version of Laravel 8, Eloquent models now come with a Prunable and MassPrunable trait to automatically delete models based on criteria.

AR
Anthony Rappa
1 min read - 8,298 views -

In the latest version of Laravel 8 (8.50 I believe), Laravel ships with 2 new traits for removing stale Eloquent models: Prunable and MassPrunable.

It came at a great time because I needed a way to remove old unfinished quizzes from the Laravel Quizzes section of my site.

I had a command and functionality stubbed out the day before this release, so I decided to scrap that and go the new route. It was super simple to accomplish.

First I added the Prunable trait to my Test model which is the model that is created anytime someone starts a new quiz. (In hindsight, probably not the best name, but I was too far along when I decided to use quiz over test.)

Then I added the following two methods to the model:

1// App\Domains\Testing\Models\Test
2 
3public function prunable()
4{
5 return static::incomplete()->where('created_at', '<=', now()->subDays(2));
6}
7 
8protected function pruning()
9{
10 $this->questions()->delete();
11}

The prunable method tells Laravel which models to choose for pruning each time the pruning job runs. In this case I want all incomplete tests that are 2 or more days old.

The pruning method is a hook to do cleanup before the model is actually deleted, in this case I'm removing all associated relationships manually.

Finally, you just set the command to run whenever you want and tell it which models it should try to prune:

1$schedule->command('model:prune', [
2 '--model' => [Test::class],
3])->daily();

It's worth noting that you do not need to specify which models to prune if they are in the default App\Models directory, but I use DDD so mine are not.

That's it! Now daily the Laravel scheduler will remove all unnecessary testing models I have which are eating up space for no reason.

Read next

What's New in Laravel: 8.58 - 8.68

Are you like me and find it impossible to find the time to keep up with the changes in Laravel on a weekly basis? In this series I'll try to roll them up periodically into one post.

AR
3 min read - 6,556 views -