How to delete file from public folder in laravel 5.1

后端 未结 17 1680
悲哀的现实
悲哀的现实 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:21

    This is the way I upload the file and save it into database and public folder and also the method I delete file from database and public folder.
    this may help you and student to get complete source code to get the task done.

    uploading file
    at the first if you save file into database by giving path public_path() once it not need to used in delete method again

    public function store_file(Request $request)
    {
       if($request->hasFile('file'))
       {
          $fileExtention = $request->file('file')->getClientOriginalExtension();
          $name = time().rand(999,9999).$request->filename.'.'.$fileExtention;
          $filePath = $request->file('file')->move(public_path().'/videos',$name);
          $video = new Video_Model;
          $video->file_path = $filePath;
          $video->filename = $request->filename;
          $video->save();
       }
       return redirect()->back();
    } 
    

    deleting file
    from database and public folder as you saved

    public function delete_file(Request $request)
    {
       $file = Video_Model::find($request->id);
       $file_path = $file->file_path;
       if(file_exists($file_path))
       {
          unlink($file_path);
          Video_Model::destroy($request->id);
       }
       return redirect()->back();
    }
    

提交回复
热议问题