当用户删除与通知相关的评论时,我如何在laravel中删除通知



我已经设置了我的网站,当另一个用户在帖子上评论说"用户名称";评论了你的帖子">

如果发表评论的用户删除了帖子,我需要能够删除此通知,就像它没有被删除一样,其他用户仍然可以点击通知,然后收到错误,因为帖子与评论不再存在。如果用户删除了评论,则应删除通知。

这就是我在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');
}

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

这是我的销毁功能:

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

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

像这样,

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

因此,它将从通知中删除。对于双击,您还将此代码放在find函数中,用户将从通知重定向到该帖子。

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

如果您在CommentCreated中跟踪数据库通知数据列中的所有$post->id$comment->id$user->id,则可以轻松完成

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

由于notifications表中的数据列是JSON TYPE,所以您可以将其作为对象处理。

最新更新