Alex
Alex

Reputation: 4774

Laravel doesn't delete directory

I have a problem deleting a directory.

I'm creating a temporary directory where I unzip a file and I want to delete it when I'm done with it.

My code looks pretty much like this:

$tempPath = storage_path('temp/'.$filemd5.'/');
Storage::makeDirectory($tempPath);
$success = Storage::deleteDirectory($tempPath);
return $success;

It doesn't return anything and the directory doesn't get deleted.

Upvotes: 6

Views: 10030

Answers (4)

Chris
Chris

Reputation: 2290

I had a similar issue, but with the following exception thrown during directory deletion:

RuntimeException(code: 0): SplFileInfo::getType(): Lstat failed for <my file name>

The culprit was Vite looking at the contents of my /storage directory for purposes of hot-reloading. Somehow that tangled up the deletion logic, resulting in the same file coming up twice for deletion, and failing the second time.

Just in case someone else has the same issue, here is the vite config I used to resolve it:

server: {
    watch: {
        ignored: ['**/storage/**'],
    },
}, 

Upvotes: 0

wuku
wuku

Reputation: 163

In my case using laravel 6.*

Storage::disk('directory')->deleteDirectory($pathDirectory);

Upvotes: 1

Mihkel Allorg
Mihkel Allorg

Reputation: 989

I think if you remove the trailing backslash from $tempPath, it might work.

$tempPath = storage_path('temp/'.$filemd5);

EDIT:

Okay, I tried different methods and looks like the class File is the most simple one.

File::makeDirectory($path)

and

File::deleteDirectory($path)

More about creating a directory and Deleting a directory

Upvotes: 10

soutoner
soutoner

Reputation: 559

Maybe you don't have enough permissions on your storage/app directory (which I think is the default one). Check that, and if that doesn't work, you can always appeal to the PHP exec function (assuming that you're on linux):

exec('rm -r ' . storage_path() . '/' . $tempPath)

UPDATE: the problem was that makeDirectory has a second int parameter that sets the permissions by default to 511 which is -r-x--x--x (i.e. read and execute, but not write). The workaround is to set the second parameter to 711 which is -rwx--x--x and you'll be able to delete the created directory. It's useful to pass the other two parameter as true because it will apply permissions recursively, and force the operation.

As Alex says, you have to use File instead of Storage. So the final code for creating directory that later you will be able to delete is:

File::makeDirectory($tempPath, 0711, true, true); 

Upvotes: 4

Related Questions