In this episode, we tackle how to actually detect when users are mentioned in a post and store that info in the database. Up to now, we've been able to search and mention users, but our app wasn't actually tracking those mentions anywhere, so it's time to fix that.
First, we create a new pivot table called mentions
, which connects posts and users. Basically, whenever someone is mentioned in a post, we store that connection so we always know who got mentioned where. We set up the migration for this table with user_id
and post_id
columns and make sure if a user or post gets deleted, their mentions get cleaned up too.
Next, we set up the relationships in our models with a belongsToMany
relationship so we can get all the users mentioned in a post or all posts a user was mentioned in.
Then, the fun part: detecting mentioned usernames in the post content. We use regex to find all the @username
mentions. There's a bit of fiddling with preg_match_all
to extract just the usernames and make sure we can handle multiple mentions in one post.
After that, we look up the user IDs for each username found and use the sync
method to update the mentions table. This way, if someone edits a post and changes who's mentioned, the database keeps up.
Finally, we test it all out by mentioning a couple of users in a post and confirming in the database that their mentions are recorded. By the end of this episode, mentions are fully detected and stored!