diff --git a/src/Console/CleanEmails.php b/src/Console/CleanEmails.php index 2631192..9ff7fbf 100644 --- a/src/Console/CleanEmails.php +++ b/src/Console/CleanEmails.php @@ -12,6 +12,8 @@ class CleanEmails extends Command protected $description = 'Clean up old incoming email logs.'; + protected $amountDeleted = 0; + public function handle() { $this->comment('Cleaning old incoming email logs...'); @@ -29,13 +31,22 @@ public function handle() /** @var InboundEmail $modelClass */ $modelClass = config('mailbox.model'); - $models = $modelClass::where('created_at', '<', $cutOffDate)->get(); + // chunk the deletion to avoid memory issues + + $this->amountDeleted = 0; - $models->each->delete(); + $modelClass::where('created_at', '<', $cutOffDate) + ->select('id') + ->chunk(100, function ($models) use ($modelClass) { + foreach ($models as $model) { + $modelInstance = $modelClass::find($model->id); + $modelInstance->delete(); + $this->amountDeleted++; + } + }); - $amountDeleted = $models->count(); - $this->info("Deleted {$amountDeleted} record(s) from the Mailbox logs."); + $this->info("Deleted {$this->amountDeleted} record(s) from the Mailbox logs."); $this->comment('All done!'); }