In this episode, we're jumping right into detecting username mentions in our comments—think of when someone writes @alex
in a comment and the system recognizes it as a mention. We start by setting up a model observer for our Comment
model in Laravel. This lets us hook into when comments are created or updated so we can check for mentions every time, including edits where mentions might be added or removed.
To pull out the usernames, we use a regular expression that matches usernames with letters, numbers, hyphens, and underscores—basically, the kinds of usernames we're allowing in the app. You'll see how we use preg_match_all
(and later adjust to PREG_SET_ORDER
for more convenient results) to extract all the mentions from a comment body, and we do some live testing to see the matches show up.
We also take a quick detour to make sure that our regex pattern lines up with the rules we're actually using for user registration. So, we update our validation to ensure only valid usernames (matching our pattern) are allowed.
By the end of the episode, you'll have logic that can find all mentioned usernames in a comment. In the next step, we'll look at actually syncing and associating those found mentions with the related database records.