How to delete file from public folder in laravel 5.1

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

    the easiest way for you to delete the image of the news is using the model event like below and the model delete the image if the news deleted

    at first you should import this in top of the model class use Illuminate\Support\Facades\Storage after that in the model class News you should do this

    public static function boot(){
        parent::boot();
    
        static::deleting(function ($news) {
              Storage::disk('public')->delete("{$news->image}");
        })
    }
    

    or you can delete the image in your controller with this command

    Storage::disk('public')->delete("images/news/{$news->file_name}");
    

    but you should know that the default disk is public but if you create folder in the public folder and put the image on that you should set the folder name before $news->file_name

提交回复
热议问题