Search code examples
laravellaravel-5.3

Laravel 5.3 - Prevent duplicate notifications for notifiable?


I have a notifiable User, user 1 and user 2 are used in this example.

If user 2 upvotes user 1 question, user 1 receives an email and a toArray notification inserted into the database, which looks like this:

public function toArray($notifiable){
    return [
        'upvoter_username' => $this->event->upvoter->username,
        'question_id' => $this->event->question->id,
        'question_title' => $this->event->question->title,
    ];
}

The issue I am facing is when user 2 goes back and downvotes the same question (no issue), and then re-upvotes the question again (issue here).

In short, user 1 receives the same email again and the notification gets inserted into the database again; user 1 should only be notified once, the first time.

How can I ensure that the notification will not notify the notifiable user 1 twice for the same upvote by user 2?


Solution

  • You will have to store the notifications in a separate table, with two fields : question_id, upvoter_id. If a row already exists for the user 2 and the question_id, dont send the email, otherwise add row and send the mail.