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

a.verrecchia's avatar

Slug with unique id reference

Hello, I'm trying to create a unique slug. However, I wanted to add a unique ID reference generated randomly at the end to avoid problems in case there are more than 1 with the same name. Is this appropriate? Is it considered a best practice?

'slug' => Str::slug($text) . '-r' . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT)

Faker result: wunsch-oreilly-and-robel-r668809

0 likes
3 replies
Talinon's avatar

@a.verrecchia

It would probably be sufficient. You could also use uniqid()

'slug' => Str::slug($text) . uniqid('-r')
1 like
lbecket's avatar

Generating a unique ID reference at the end of a slug is a common approach for ensuring uniqueness and your implementation using Str::slug and str_pad looks appropriate and should work as expected.

It's important to note that while this approach can help prevent duplicate slugs, it may not be the most user-friendly or SEO-friendly solution. Adding a random string of characters to a slug will make it more difficult for users to remember or type the URL, and it may not be as search engine-friendly as a more descriptive slug. That may not be of particular concern for you, but it's worth noting.

To balance uniqueness with user-friendliness and SEO-friendliness, you could check the uniqueness of the slug against existing slugs in the database and only generate a new one if necessary, without relying on a random string of characters.

1 like
a.verrecchia's avatar

@lbecket Let's say the user doesn't have to remember the URL by heart, but you still pointed out something that is important. I will take care to do as you described and apply a unique ID at the end as written in the above mentioned answer.

Please or to participate in this conversation.