I am trying to write an artisan command that deletes any folders that are 50 or more days old. I am unable to do thiswith timestamps, but the folder names are labelled with the date i.e 2022-01-14 (Y-m-d)
collections/2022-01-14
collections/2022-01-13
collections/2022-01-12
This is what I currently have, but it is not doing anything and not returning any errors, it just doesnt work
collect(Storage::directories('collections/'))
->each(function ($directory) {
if ($directory < now()->subDays(50)->format('Y-m-d')) {
Storage::deleteDirectory($directory);
}
});
CodePudding user response:
You are comparing a string with another string, use Carbon logic instead. Parse the directory name to a Carbon instance, and use less than equal lte()
to compare.
collect(Storage::directories('collections/'))
->each(function ($directory) {
$directoryDate = Str::after($directory, '/');
if (Carbon::parse(directoryDate)->lte(now()->subDays(50))) {
Storage::deleteDirectory($directory);
}
});
EDIT
Directory came with full path, finding everything after '/'
would get you the date part. Using the string helper after()
.