0

What I am trying to achieve is to delete multiple photos from one delete command, but it only delete the record from the database, but unable to delete the file in my local storage. I am trying to use unlink() method in order to make this to work. I hope somebody would enlighten me where that I made my mistake. Thank you!

Delete method


//There are 8 columns of image, the database record is wiped, but not in the local storage.

public function destroy(Gallery $gallery){

        for ($i = 1; $i < 9; $i++) {
            $path = storage_path('app/public/' . $gallery->image_ . $i);
            
            if (file_exists($path)) {
                @unlink($path);                
            }
        }

    $gallery->delete();

}
cleopatez
  • 197
  • 1
  • 1
  • 17
  • 3
    **WARNING**: Using the error-suppressing YOLO operator (`@`) obscures problems with your code and makes debugging issues like this a whole lot more complicated. That's a tool of last resort and should only be used in exceptional circumstances. You should display an error message for the user, log a problem, initiate some kind of retry, or all of these things in conjunction. – tadman Feb 16 '21 at 21:52
  • Noted, sir. I will opt to something such as File::delete to execute the same function. @tadman – cleopatez Feb 16 '21 at 21:57
  • I assume you are trying to use the property named `image_1`, `image_2`, etc on `$gallery`? – lagbox Feb 16 '21 at 21:57
  • That function is fine, it's just the `@` that's problematic. – tadman Feb 16 '21 at 21:57
  • Instead of randomly guessing what files exist and assuming that there will be 1...8 of them, why not use [`glob()`](https://www.php.net/manual/en/function.glob.php) to find out what's actually there? Like [this example](https://stackoverflow.com/questions/12254391/delete-files-using-wildcard-exec-vs-unlink). – tadman Feb 16 '21 at 21:59
  • Yep, it's meant to be like that, sir. @lagbox – cleopatez Feb 16 '21 at 22:01
  • Aaah understood. I'll give it a try on glob(). Thank you for the suggestion. @tadman – cleopatez Feb 16 '21 at 22:02
  • 1
    then you need to do something like this `$gallery->{"image_$i"}` so it knows the property is `'image_1'` etc – lagbox Feb 16 '21 at 22:05
  • 1
    That sorts it out! Thank you very much @lagbox – cleopatez Feb 16 '21 at 22:18

0 Answers0