How to delete folder (and its content) not under storage/app in Laravel?

Viewed 431

I know we can use Storage::delete() or File::delete to delete folders and/or files in laravel, but this seems not working for folders directly under storage, I mean storage/tmp by example. It only works for storage/app. How to deal with this?

if (file_exists( storage_path() . '/tmp/file1'.'.pdf' )) {
     File::delete(storage_path() . '/tmp/file1'.'.pdf') );
}

Thanks

2 Answers

You can define a new disk in config/filesystems.php with the storage folder as root:

'disks' => [

    ...

    'storage' => [
        'driver' => 'local',
        'root' => storage_path(),
    ],

    ...

],

Then you can delete a folder, such as tmp, like this:

Storage::disk('storage')->deleteDirectory('tmp');

that happen due you have the default configuration in filesystems config, go to config folder config/filesystems.php

and in the disk property you can modify or add a new key

When you use the Storage directly without call the disk method Laravel will use the default disk called 'local'

'disks' => [
    'local' => [
        'driver' => 'local',
        'root' => storage_path('app'),
     ]

How you can see the root key start in app folder, so when you use Storage::delete() always will delete all inside app folder, the solution can be alter de root key of local disk

'disks' => [
    'local' => [
        'driver' => 'local',
        'root' => storage_path(),
     ]

Of this way now when you call the Storage the root will by storage path directly, but the best way its add a new key and don't overwrite the default config

'disks' => [
    'storage' => [
        'driver' => 'storage',
        'root' => storage_path(),
     ]

And now you can use the new disk of this way:

Storage::disk('storage')->delete('x')
Related