Laravel 5.4: how to delete a file stored in storage/app

后端 未结 8 1626
臣服心动
臣服心动 2020-12-30 00:22

I want to delete a file that is stored in storage/app/myfolder/file.jpg. I have tried the following codes but none of this works:

use File    
$file_path = u         


        
8条回答
  •  不思量自难忘°
    2020-12-30 00:57

    You could either user Laravels facade Storage like this:

    Storage::delete($file);
    

    or you could use this:

    unlink(storage_path('app/folder/'.$file));
    

    If you want to delete a directory you could use this:

    rmdir(storage_path('app/folder/'.$folder);
    

    One important part to mention is that you should first check wether the file or directory exists or not.

    So if you want to delete a file you should probably do this:

    if(is_file($file))
    {
        // 1. possibility
        Storage::delete($file);
        // 2. possibility
        unlink(storage_path('app/folder/'.$file));
    }
    else
    {
        echo "File does not exist";
    }
    

    And if you want to check wether it is a directory do this:

    if(is_dir($file))
    {
        // 1. possibility
        Storage::delete($folder);
        // 2. possibility
        unlink(storage_path('app/folder/'.$folder));
        // 3. possibility
        rmdir(storage_path('app/folder/'.$folder));
    }
    else
    {
        echo "Directory does not exist";
    }
    

提交回复
热议问题