1

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

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

这就是我创建评论并在我的 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');

}
4

2 回答 2

0

如果您在 CommentCreatedTrack all of$post->id和数据库通知数据列中$comment->id​​,$user->id您可以轻松地做到这一点

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

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

于 2020-12-30T13:26:12.657 回答
0

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

像这样的东西,

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

因此,何时将其从通知中删除。并且为了仔细检查,您还将此代码放在查找功能中,用户从通知重定向到该帖子。

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

于 2020-12-29T14:24:05.337 回答