Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

timokfine's avatar

@username tagging

Hey, guys. I'm looking for some direction on how to on build username tagging into Laravel.

The basic process would be a user tags another user in a forum post or comment using @username. There would be a popup with username suggestions like in Esotalk, and once posted, a notification would be sent to the user who was tagged.

I can handle the notifications side of things, but I'm just curious as to the best approach for the tagging process. I imagine it has something to do with regular expressions?

Thanks!

0 likes
5 replies
mikebronner's avatar

Some thoughts off the top of my head, I have no idea if they are good or not, just brainstorming :)

  • Use jQuery UI autocomplete
  • When user types a "@" surround that by a specific span with ID, perhaps use a random number or some other way to make it unique
  • initialize that span as an autocomplete element
  • user continues typing, updating the span, causing the autocomplete to trigger database lookups (you can point the source parameter to a JSON API, basically a route using set up using the API lessons on LaraCasts)

Then in the controller all you have to do is look for a user beginning with the term passed in by jquery UI autocomplete.

timokfine's avatar

Thanks, Mike. I'm going to revisit this through the week. Haha.

david's avatar

I have a helper function like this:

function link_usernames($text)
{
    return preg_replace('~(^|\s)@([[:alnum:]_]+)~', '$1<a href="'.url('$2').'/">@$2</a>', $text);
}

Just change the URL to link how you'd like. :-)

3 likes
timokfine's avatar

@david Awesome!

Is there any way to make Markdown automatically process @usernames into the above? I'm using the graham-campbell/markdown package. Can you add custom rules or something?

david's avatar

The simplest way is to just pass your converted Markdown into that helper. I also have a @markdown Blade extension that I use so I would be tempted to call the linking function in there.

Please or to participate in this conversation.