【问题标题】:how do i delete a notification in laravel when a user deletes the comment related to the notification当用户删除与通知相关的评论时,如何在 laravel 中删除通知
【发布时间】:2021-04-06 03:45:43
【问题描述】:

我已将我的网站设置为当另一个用户在帖子上说“用户名”评论了您的帖子时向帖子所有者发送通知

如果发表评论的用户删除了帖子,就好像它没有被删除一样,我需要能够删除此通知,其他用户仍然可以单击通知,然后由于帖子不再存在而出现错误如果用户删除评论,则应删除通知。

这就是我创建评论并在我的 CommentsController 中发送通知的方式:

public function store(Request $request, $post_id)
{
    $this->validate($request, array(
        'comment' => 'required|min:2|max:2000',
        'email' => 'required',
        'name' => 'required'
    ));

    $post = Post::find($post_id);
    $user = Auth::user();

    $comment = new Comment();
    $comment->name = $request->name;
    $comment->email = $request->email;
    $comment->comment = $request->comment;
    $comment->approved = true;
    $comment->post_id = $post->id;
    $comment->user_id = $user->id;
    $comment->post()->associate($post);
    $comment->save();

    User::find($post->user_id)->notify(new CommentCreated($user, $post, $comment));
    return redirect()->back()->with('success','Comment Created');
}

所以我认为我必须删除销毁函数中的通知,但我不知道该怎么做。

这是我的销毁函数:

public function destroy($id)
{
    $comment = Comment::find($id);
    if(auth()->user()->id == $comment->user_id || auth()->user()->role == 'Admin') {
        $comment->delete();
        return redirect()->back()->with('success','Comment Removed');
    }
    
    return redirect('/posts')->with('error','Unauthorised Page');

}

【问题讨论】:

  • 我真的不明白我将如何使用与我的示例相关的内容
  • 如果表通知上有一个外键指向评论id,那么您可以添加引用操作“ON DELETE CASCADE”,以便在删除评论时自动删除通知。
  • 好吧,如果您创建一个新通知,例如CommentDeleted你可以收听那个并删除客户端的所有通知(注意我真的在推测你的系统在这里是如何工作的,因为没有足够的信息可以继续)

标签: php laravel destroy laravel-notification


【解决方案1】:

如果您在CommentCreated 跟踪数据库通知数据列中​​的所有$post->id$comment->id$user->id,您可以轻松做到这一点

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

由于通知表中的数据列是JSON TYPE,所以在eloquent中可以作为对象处理。

【讨论】:

    【解决方案2】:

    您需要在销毁函数中添加逻辑以删除与该帖子相关的通知。

    像这样的,

    Notification::find('post_id', $post->id)->delete(); // can be single or multiple change according to your logic
    

    所以它什么时候会从通知中删除。 对于仔细检查,您还可以将此代码放在查找功能中,用户从通知重定向到该帖子。

    所以您需要使用findOrFailwhereHas 来检查帖子是否存在。如果没有并且通知仍然存在,则删除该通知,然后根据您的流程重定向到适当的页面。

    【讨论】:

      猜你喜欢
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 2021-10-04
      • 2014-03-27
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      相关资源
      最近更新 更多