删除laravel中不同文件夹的图像

时间:2016-12-12 07:27:06

标签: php laravel laravel-5.3 laravel-blade

我已在公共/图片内的不同子文件夹中保存了帖子的图片,例如featured_image (public / images / featured_image) banner(public /图像/横幅)即可。我想在删除横幅时删除与帖子相关的图片(featured_image和banner)。

这是filesystem.php

中的设置
'local' => [
  'driver' => 'local',
  'root' => public_path('images/'),
],

我正在尝试删除与此相关的帖子和​​图片:

public function destroy($id)
{
    //
    $tour = Tour::find($id);
    $tour->country()->detach();
    Storage::delete('featured_image/$tour->featured_image');
    Storage::delete('banner/$tour->banner');
    $tour->delete();

    Session::flash('success', 'The tour is sucessfully deleted.');
    return redirect()->route('tours.index');
}

该帖子已成功删除,但图片未从该文件夹中删除。请提出可能的解决方案。

2 个答案:

答案 0 :(得分:1)

应该是

Storage::delete('images/featured_image/' . $tour->featured_image);
Storage::delete('images/banner/' . $tour->banner);

如果这不起作用......你也可以这样做。

$images = [
  'featured_image' => public_path('images/featured_image/' . $tour->featured_image),
  'banner_image' => public_path('images/banner/' . $tour->banner),
];

foreach($images as $image) {
  if(file_exists($image)) {
    unlink($image);
  }
}

答案 1 :(得分:0)

我使用File:delete();方法完成了这项工作。

public function destroy($id)
{

    $tour = Tour::find($id);
    $tour->country()->detach();
    File::delete(public_path('/images/featured_image/' . $tour->featured_image));
    File::delete(public_path('/images/banner/' . $tour->banner));
    $tour->delete();

    Session::flash('success', 'The tour is sucessfully deleted.');
    return redirect()->route('tours.index');
}