How to unlink multiple files in laravel?

Member

by lew , in category: PHP Frameworks , 3 months ago

How to unlink multiple files in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 3 months ago

@lew 

To unlink multiple files in Laravel, you can use the Storage facade to delete the files. Here is an example code snippet to unlink multiple files in Laravel:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
use IlluminateSupportFacadesStorage;

// Array of file paths to unlink
$files = [
    'path/to/file1.jpg',
    'path/to/file2.jpg',
    'path/to/file3.jpg',
];

// Loop through each file and unlink it
foreach ($files as $file) {
    if (Storage::exists($file)) {
        Storage::delete($file);
        echo "File $file unlinked successfully <br>";
    } else {
        echo "File $file does not exist <br>";
    }
}


In this code snippet, we first define an array of file paths that we want to unlink. We then loop through each file path and check if the file exists using the exists method of the Storage facade. If the file exists, we use the delete method to unlink it. Finally, we output a message indicating whether the file was unlinked successfully or if it does not exist.


Make sure to adjust the file paths in the $files array to match the actual file paths you want to unlink.