Skip to content

Commit 6b9a840

Browse files
committed
Fix memory limit issues when running mailbox:clean
1 parent b066ab5 commit 6b9a840

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

src/Console/CleanEmails.php

+15-4
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ class CleanEmails extends Command
1212

1313
protected $description = 'Clean up old incoming email logs.';
1414

15+
protected $amountDeleted = 0;
16+
1517
public function handle()
1618
{
1719
$this->comment('Cleaning old incoming email logs...');
@@ -29,13 +31,22 @@ public function handle()
2931
/** @var InboundEmail $modelClass */
3032
$modelClass = config('mailbox.model');
3133

32-
$models = $modelClass::where('created_at', '<', $cutOffDate)->get();
34+
// chunk the deletion to avoid memory issues
35+
36+
$this->amountDeleted = 0;
3337

34-
$models->each->delete();
38+
$modelClass::where('created_at', '<', $cutOffDate)
39+
->select('id')
40+
->chunk(100, function ($models) use ($modelClass) {
41+
foreach ($models as $model) {
42+
$modelInstance = $modelClass::find($model->id);
43+
$modelInstance->delete();
44+
$this->amountDeleted++;
45+
}
46+
});
3547

36-
$amountDeleted = $models->count();
3748

38-
$this->info("Deleted {$amountDeleted} record(s) from the Mailbox logs.");
49+
$this->info("Deleted {$this->amountDeleted} record(s) from the Mailbox logs.");
3950

4051
$this->comment('All done!');
4152
}

0 commit comments

Comments
 (0)