duanjiu6697 2018-01-29 15:57
浏览 48
已采纳

删除评论和相关图像

I'm trying to delete single user comments and the pictures related with them, by deleting them from both the database records and storage. Unfortunately I keep getting errors. Below is the code I have so far.

Tables: Comments: id, comment, user_id, person_id pictures: id, image, comment_id, user_id, person_id

Relationships: Comment:

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

pictures:

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

Controller:

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');
} 

Any ideas?

  • 写回答

3条回答 默认 最新

  • drbae3964 2018-01-29 16:03
    关注

    You need to use pluck() to load images file names:

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

    Then delete these files:

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

    This is just an example, you need to put correct column name instead of filename and build the correct path to the images.

    To delete images from DB:

    $comment->images()->delete();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)