簡體   English   中英

Laravel 刪除所有早於某個日期的目錄

[英]Laravel delete all directories that are older than a certain date

我正在嘗試編寫一個工匠命令來刪除任何 50 天或更長時間的文件夾。 我無法使用時間戳執行此操作,但文件夾名稱標有日期,即 2022-01-14 (Ymd)

collections/2022-01-14
collections/2022-01-13
collections/2022-01-12

這是我目前擁有的,但它沒有做任何事情,也沒有返回任何錯誤,它只是不起作用

collect(Storage::directories('collections/'))
    ->each(function ($directory) {
        if ($directory < now()->subDays(50)->format('Y-m-d')) {
            Storage::deleteDirectory($directory);
        }
    });

您正在將一個字符串與另一個字符串進行比較,請改用 Carbon 邏輯。 將目錄名稱解析為 Carbon 實例,並使用小於等於lte()進行比較。

collect(Storage::directories('collections/'))
    ->each(function ($directory) {
        $directoryDate = Str::after($directory, '/');
        if (Carbon::parse(directoryDate)->lte(now()->subDays(50))) {
            Storage::deleteDirectory($directory);
        }
    });

編輯

目錄帶有完整路徑,在'/'之后查找所有內容都會為您提供日期部分。 使用字符串助手after()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM