Skip to content

Commit

Permalink
Fix memory limit issues when running mailbox:clean
Browse files Browse the repository at this point in the history
  • Loading branch information
mechelon committed Apr 3, 2024
1 parent b066ab5 commit 6b9a840
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/Console/CleanEmails.php
Original file line number Diff line number Diff line change
Expand Up @@ -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...');
Expand All @@ -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!');
}
Expand Down

0 comments on commit 6b9a840

Please sign in to comment.