Laravel File Storage delete all files in directory

此生再无相见时 提交于 2019-12-10 01:57:02

问题


Is there a way to delete all files in specific directory. I'm trying to clear all my files in my created folder backgrounds in storage\app\backgrounds but in docs seems no method for delete all.

Storage::delete('backgrounds\*.jpg');

回答1:


I don't think if this is the best way to solve this. But I solved mine calling

use Illuminate\Filesystem\Filesystem;

Then initiate new instance

$file = new Filesystem;
$file->cleanDirectory('storage/app/backgrounds');



回答2:


    use Illuminate\Support\Facades\Storage;

    // Get all files in a directory
    $files =   Storage::allFiles($dir);

    // Delete Files
    Storage::delete($files);



回答3:


You can use Filesystem method cleanDirectory

$success = Storage::cleanDirectory($directory);

Please see documentation for more information:

https://laravel.com/api/5.5/Illuminate/Filesystem/Filesystem.html#method_cleanDirectory




回答4:


In Laravel 5.7 you can empty a directory using the Storage facade like so:

Storage::delete(Storage::files('backgrounds'));

$dirs = Storage::directories('backgrounds');

foreach ($dirs as $dir) {
    Storage::deleteDirectory($dir);
}

The delete() method can receive an array of files to delete, while deleteDirectory() deletes one directory (and its contents) at a time.

I don't think it's a good idea to delete and then re-create the directory as that can lead to unwanted race conditions.




回答5:


In Laravel 5.8 you can use:

Storage::deleteDirectory('backgrounds');

Remember to include:

use Illuminate\Support\Facades\Storage;



回答6:


I'm handling this by deleting the whole directory as I don't need it. But if, for any case, you need the directory you should be good by just recreating it:

$d = '/myDirectory'
Storage::deleteDirectory($d);
Storage::makeDirectory($d);



回答7:


//You can use Illuminate\Filesystem\Filesystem and it's method cleanDirectory('path_to_directory).
For Example:
    $FolderToDelete = base_path('path_to_your_directory');
    $fs = new \Illuminate\Filesystem\Filesystem;
    $fs->cleanDirectory($FolderToDelete);   
    //For Delete All Files From  Given Directory.
    $succes = rmdir($FolderToDelete);
    //For Delete Directory
    //This Method Works for me

#Laravel 
#FileManager
#CleanDirectory


来源:https://stackoverflow.com/questions/47007356/laravel-file-storage-delete-all-files-in-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!