34

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');
ßiansor Å. Ålmerol
  • 2,849
  • 3
  • 22
  • 24

8 Answers8

54

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');
ßiansor Å. Ålmerol
  • 2,849
  • 3
  • 22
  • 24
26

for Laravel >= 5.8

    use Illuminate\Support\Facades\Storage;

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

    // Delete Files
    Storage::delete($files);
Toby Allen
  • 10,997
  • 11
  • 73
  • 124
20

Just use it.

 File::cleanDirectory($direction);
Amir Kaftari
  • 1,305
  • 14
  • 13
  • This is the way. – user2094178 Feb 05 '20 at 02:40
  • 2
    Note he is using the Facade 'File' (`use File;` or better `use Illuminate\Support\Facades\File;`). You can also use this in conjunction with Storage disks: `File::cleanDirectory(Storage::disk('some-disk')->path(''));` – Ken Aug 10 '21 at 07:16
6

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

porkbrain
  • 720
  • 5
  • 16
5

In Laravel 5.8 you can use:

Storage::deleteDirectory('backgrounds');

Remember to include:

use Illuminate\Support\Facades\Storage;
cespon
  • 5,630
  • 7
  • 33
  • 47
3

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.

Soulriser
  • 419
  • 8
  • 16
1

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);
brnd0
  • 338
  • 6
  • 15
0
//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