问题描述
我已将我的网站设置为当其他用户对帖子发表评论时向帖子所有者发送通知,说“该用户的姓名”对您的帖子发表了评论
如果发表评论的用户删除了帖子,就好像它没有被删除一样,我需要能够删除此通知,其他用户仍然可以点击通知,然后因为帖子不再存在而收到错误消息如果用户删除评论,则应删除通知。
这是我创建评论并在我的 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');
}
解决方法
您需要在 destroy 函数中添加逻辑以删除与该帖子相关的通知。
像这样,
Notification::find('post_id',$post->id)->delete(); // can be single or multiple change according to your logic
那么它什么时候会从通知中删除。 对于仔细检查,您还将此代码放在查找功能中,用户从通知重定向到该帖子。
因此您需要使用 findOrFail
或使用 whereHas
来检查帖子是否存在。如果没有并且通知仍然存在,则删除该通知,然后根据您的流程重定向到适当的页面。
如果您在 CommentCreated
中跟踪数据库通知数据列中的所有 $post->id
、$comment->id
和 $user->id
,您可以轻松做到这一点
Notification::where('data->comment_id',$comment->id)->delete();
由于通知表中的数据列是 JSON TYPE ,因此您可以将其作为 eloquent 中的对象处理。