DEV Community

Morcos Gad
Morcos Gad

Posted on

Prune and Mass Prune Models - Laravel

Let's learn this wonderful feature. You found this wonderful resource https://www.youtube.com/watch?v=557_IL3d9V8 Let's assume that you have some old recordings that you want to delete from the database. Here comes this feature.
First we go to the Model in which we want to implement this feature and use Prunable

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;

class Flight extends Model
{
    use Prunable;

    public function prunable()
    {
        return static::where('created_at', '<=', now()->subMonth())->whereNull('email_verified_at');
    }
}
Enter fullscreen mode Exit fullscreen mode

After that it is possible to use command

php artisan model:prune
Enter fullscreen mode Exit fullscreen mode

Here we see the pruning function and when I use it in the Model, we explain what we want to do after deleting the records

protected function pruning()
{
    echo 'Pruning ' . $this->name . PHP_EOL;
}
Enter fullscreen mode Exit fullscreen mode

We also use the schedule to execute a command every certain period, which makes more sense in your future projects

protected function schedule(Schedule $schedule)
{
    $schedule->command('model:prune')->daily();
}
Enter fullscreen mode Exit fullscreen mode

Let's move to Mass Pruning, which deletes records once, but there is a flaw in it nor will the deleting and deleted model events be dispatched. This is because the models are never actually retrieved before deletion, thus making the pruning process much more efficient Here we use MassPrunable

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\MassPrunable;

class Flight extends Model
{
    use MassPrunable;

    public function prunable()
    {
        return static::where('created_at', '<=', now()->subMonth());
    }
}
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code as much as I enjoyed sharing it with you. To dig deeper, visit these resources
https://laravel.com/docs/8.x/eloquent#pruning-models
https://laravel.com/docs/8.x/eloquent#mass-pruning
https://hbakouane.medium.com/models-pruning-in-laravel-8-50-0-explained-8fad5017f9b0

Top comments (1)

Collapse
 
robinbastiaan profile image
Robin Bastiaan

When you have a model with the MassPrunable trait, it still get deleted using the command $schedule->command('model:prune')->daily(); so nothing needs to be changed there.

This means that if you do not need the 'pruning', deleting nor the deleted model events be dispatched you can safely change the trait of the model to MassPrunable to gain a performance boost.

Also note you can only have one of the two traits at the same time, because they have the same names for methods and PHP does not allow that.