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());
}
}
Then we do the actual cleaning
php artisan model:prune
If you want to count the number of records that have been deleted
php artisan model:prune --pretend
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();
}
I hope you enjoyed the code.
Source :- https://laravel.com/docs/8.x/eloquent#pruning-models
Top comments (0)