Periodic cleaning of models from obsolete records

To periodically clean models of obsolete records. With this trait, Laravel will do this automatically, only you need to adjust the frequency of the model:prune command in the Kernel class.

1use Illuminate\Database\Eloquent\Model;
2use Illuminate\Database\Eloquent\Prunable;
3class Flight extends Model
4{
5 use Prunable;
6 /**
7 * Get the prunable model query.
8 *
9 * @return \Illuminate\Database\Eloquent\Builder
10 */
11 public function prunable()
12 {
13 return static::where('created_at', '<=', now()->subMonth());
14 }
15}

Also, in the pruning method, you can set the actions that must be performed before deleting the model:

1protected function pruning()
2{
3 // Removing additional resources,
4 // associated with the model. For example, files.
5 
6 Storage::disk('s3')->delete($this->filename);
7}

Tip given by @PascalBaljet

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord