DEV Community

Morcos Gad
Morcos Gad

Posted on

Laravel Prunable Models

A new feature that appeared in laravel 8.50 is to delete old records once or periodically

<?php

namespace App\Models;

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

class Flight extends Model
{
    use Prunable;

    /**
     * Get the prunable model query.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function prunable()
    {
        return static::where('created_at', '<=', now()->subMonth());
    }
}
Enter fullscreen mode Exit fullscreen mode

Then we do the actual cleaning

php artisan model:prune
Enter fullscreen mode Exit fullscreen mode

If you want to count the number of records that have been deleted

php artisan model:prune --pretend
Enter fullscreen mode Exit fullscreen mode

you should schedule the model:prune

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->command('model:prune')->daily();
}
Enter fullscreen mode Exit fullscreen mode

I hope you enjoyed the code.
Source :- https://laravel.com/docs/8.x/eloquent#pruning-models

Top comments (0)