删除评论和相关图像

时间:2018-01-29 15:57:49

标签: php laravel laravel-5 eloquent laravel-5.5

我正在尝试删除单个用户评论以及与之相关的图片,方法是从数据库记录和存储中删除它们。不幸的是我不断收到错误。下面是我到目前为止的代码。

表: 评论:id,comment,user_id,person_id 图片:id,image,comment_id,user_id,person_id

关系: 评论:

public function pictures()
{
    return $this->hasMany('App\Picture', 'comments_id', 'id');
} 

图片:

   public function comments()
    {
        return $this->belongsTo('App\Comment', 'comments_id');
    }

控制器:

public function destroy($id)
{
    $comment = Comment::find($id);
    Storage::delete($comment->pictures());

    $comment->delete();
    Session::flash('success', 'Your comment and pictures were deleted');

    return redirect()->route('home');
} 

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您需要使用pluck()来加载图像文件名:

$files = $comment->pictures()->pluck('filename');

然后删除这些文件:

foreach ($files as $file) {
    Storage::delete(storage_path('images/' . $file));
}

这只是一个示例,您需要输入正确的列名而不是filename并构建图像的正确路径。

从DB中删除图像:

$comment->images()->delete();

答案 1 :(得分:2)

$comment->pictures()返回关系的定义,而不是相关图片。如果你想删除所有图片,你需要迭代它们并逐个删除:

$comment = Comment::find($id);
foreach ($comment->pictures as $picture) {
  // delete picture from storage
  Storage::delete($picture->id); //or whatever field is used as key in the storage
  // delete picture from the database - might be optional if you've set a cascade on delete behaviour in your foreign key definition
  $picture->delete();
}

答案 2 :(得分:0)

您需要提供filename图片才能从storage删除图片。

$comment = Comment::find($id);
foreach($comment->pictures as $picture)
        Storage::delete($picture->image);

Picture::where('comment_id',$comment->id)->delete();
$comment->delete();