Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to store a unique URL Slug?

Tags:

url

database

slug

I'm trying to generate some url 'slugs' for my website. It's based upon a single piece of user generated text.

Now, i have made my own slug method, so i'm not after some code for that.

What i'm wondering is where is the best place to determine if this slug is unique and then insert it because the slug field is a Unique Key Index.

Originally, i had a trigger on any insert (against the table) so when the data is entered, the slug is then determined. I had a function that checked for the number of records that contained the user's text (not the slug) and then generated the slug and added the record count + 1 to the end of the new slug.

eg.

5 records are found in the table with the same User generated content. the slug for this now the slug-text with a 6 added to the end.

Flaws: if the user changes their text, the slug doesn't change.

Anyways, i'm wondering if other people have delt with this issue before and found any ways to fix it?

like image 455
Pure.Krome Avatar asked Jan 12 '09 03:01

Pure.Krome


2 Answers

I kinda like the way stackoverflow does it. Which is to put both the ID and the slug into the url. Now the slug no longer has to be unique. I believe hulu.com does it this way as well. I think it's a practical solution to the problem.

like image 131
airportyh Avatar answered Oct 20 '22 01:10

airportyh


Most sites don't change the slug for the reason that if a user edits her title it shouldn't break any links to the post that have already been made.

like image 32
alxp Avatar answered Oct 19 '22 23:10

alxp