In this episode, we're tackling how to notify users when they're mentioned somewhere, like in a comment. The idea is that whenever someone is tagged, we want to send them a notification—maybe by email, Slack, SMS, or whatever makes sense for your app.
But the tricky part is figuring out when to send the notification. If you just look for every comment update, you might end up notifying users over and over for the same thing, which would be super annoying. What we really want is to listen for the exact moment when the mention relationship (the so-called "pivot" in Laravel) gets attached.
By default, Laravel doesn't really make it easy to listen for these attached pivot events. To solve this, we pull in a package (one that's even used on the CodeCourse website!) that adds this missing functionality for us. We go through installing the package, pulling in its trait on our Comment model, and then use a pivotAttached
event inside a static booted
method. This gives us what we need: now we know when a user has actually been mentioned, and we have all the info—like the comment, relation name, and the IDs of who was mentioned.
Finally, we run through some examples to see exactly what data we get in our event, and set things up so you'll be ready to actually send the notifications in the next episode. Basically, by the end, you've got the right event firing just when someone is mentioned (and not on every update), so you can notify them at the perfect moment!