In this episode, we take all those usernames we found earlier with our regular expression matching and actually sync them up in our database. The goal is to link comments directly to the user accounts they mention, not just by username, but via their user IDs. This will allow us to know exactly which users were mentioned in which comments, making things a lot more powerful and flexible down the line.
We start by introducing a pivot table called comment_mentions
, which connects comment IDs to user IDs—the standard Laravel way would use something like comment_user
, but we want our relationship named more clearly. We set up the Eloquent relationships, making sure each comment can have many mentioned users, and vice versa.
After that, we move into syncing: for each comment, we pluck out all the usernames that got mentioned, look up those users in the database, grab their IDs, and then sync those IDs with the comment through our new relationship. If a username doesn’t exist, no worries—it just won’t create a mention for that name. We do a few quick manual checks to make sure everything is working, add some dd()
s to inspect what we’re sending, and confirm that only real users get synced.
Finally, there’s a chat about why it’s useful to store this info in the database—not just for notifications, but so users can later see all the mentions across the site. Next time, we’ll write some tests to make sure this all works automatically!