How to delete file from public folder in laravel 5.1

后端 未结 17 1629
悲哀的现实
悲哀的现实 2020-11-30 09:02

I want to delete a News from database and when I hit the delete button all data from database deleted but the image is remains in upload folder. So, how do I this to work. t

相关标签:
17条回答
  • 2020-11-30 09:23

    Try to use:

    unlink('.'.Storage::url($news->photo));
    

    Look the dot and concatenation before the call of facade Storage.

    0 讨论(0)
  • 2020-11-30 09:26
    public function destroy($id) {
        $news = News::findOrFail($id);
        $image_path = app_path("images/news/".$news->photo);
    
        if(file_exists($image_path)){
            //File::delete($image_path);
            File::delete( $image_path);
        }
        $news->delete();
        return redirect('admin/dashboard')->with('message','خبر موفقانه حذف  شد');
    }
    
    0 讨论(0)
  • 2020-11-30 09:27

    this method worked for me
    First, put the line below at the beginning of your controller:

    use File;
    

    below namespace in your php file Second:

     $destinationPath = 'your_path';
     File::delete($destinationPath.'/your_file');
    

    $destinationPath --> the folder inside folder public.

    0 讨论(0)
  • 2020-11-30 09:33

    You could use PHP's unlink() method just as @Khan suggested.

    But if you want to do it the Laravel way, use the File::delete() method instead.

    // Delete a single file

    File::delete($filename);
    

    // Delete multiple files

    File::delete($file1, $file2, $file3);
    

    // Delete an array of files

    $files = array($file1, $file2);
    File::delete($files);
    

    And don't forget to add at the top:

    use Illuminate\Support\Facades\File; 
    
    0 讨论(0)
  • 2020-11-30 09:34

    Use the unlink function of php, just pass exact path to your file to unlink function :

    unlink($file_path);
    

    Do not forget to create complete path of your file if it is not stored in the DB. e.g

    $file_path = app_path().'/images/news/'.$news->photo;
    
    0 讨论(0)
  • 2020-11-30 09:37

    First make sure the file exist by building the path

    if($request->hasFile('image')){
        $path = storage_path().'/app/public/YOUR_FOLDER/'.$db->image;
          if(File::exists($path)){
              unlink($path);
          }
    
    0 讨论(0)
提交回复
热议问题