Introducing Laravel Quizzes! Play now

Pruning Laravel Models

Pruning Laravel Models


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:

// App\Domains\Testing\Models\Test

public function prunable()
{
    return static::incomplete()->where('created_at', '<=', now()->subDays(2));
}

protected function pruning()
{
    $this->questions()->delete();
}

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:

$schedule->command('model:prune', [
    '--model' => [Test::class],
])->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.

Anthony Rappa

By Anthony Rappa

Hello! I'm a full stack developer from Long Island, New York. Working mainly with Laravel, Tailwind, Livewire, and Alpine.js (TALL Stack). I share everything I know about these tools and more, as well as any useful resources I find from the community. You can find me on GitHub and LinkedIn.