Models Pruning in Laravel 8.50.0 explained

Haytam Bakouane
2 min readJul 15, 2021

Check out my blog for more articles like this: https://hbakouane.dev/blog

Laravel has released a new feature in its new version 8.50.0 which is called “Models Pruning”, this feature will take care of the old records that you don’t want to exist anymore in your database, with this new feature you will not need to generate a new Job class for your models, You will be running just one command in your App\Console\Kernel.

Now, Let’s say we want to delete the old records of an Event Model which we don’t need anymore, we would like to delete all the records that are older than one week:

// App\Models\Event;use Illuminate\Database\Eloquent\Prunable;class Event 
{
/**
* Get the prunable model query.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function prunable()
{
return static::where('created_at', '<=', now()->subDays(7));
}
}

Let’s say we want to execute some kind of operations while “pruning” the records:

protected function pruning()
{
// Eg: Send email to admin
}

Now let’s make this work:

// App\Console\Kernelprotected function schedule(Schedule $schedule)
{
$schedule->command('model:prune')->weekly();
}

In case we want to “prun” records of more than one record

$schedule->command('model:prune', [
'--model' => [Event::class, Booking::class],
])->daily();

See more features in this release (8.50.0): https://www.youtube.com/watch?v=Vr58h0IKjkM

Thanks for reading!

Check out my blog for more articles like this: https://hbakouane.dev/blog

Read More:

Integration of Laravel + VueJs + AdminLTE made easy

Models Pruning in Laravel 8.50.0 explained

5 Javascript libraries that will help you build your stunning Portfolio

A Laravel SaaS Boilerplate to start working on your next project

--

--

Haytam Bakouane

It's Haytam here, I work with Laravel/Vue, I seek to learn new things daily as possibly as I could, Now I'm learning Tailwind, such a great framework!