将项目ID附加到slug或使用Laravel在MySQL中找到slug

I currently have a URI's which contain a slug instead of a primary key. I then find the corresponding item by searching for that string. (they are TV show names so they are pretty much unique)

Example:/show/big-bang-theory/episode/01

I then return the corresponding show

public function getBySlug($slug)
{
    return Show::where('slug', '=', $slug)->firstOrFail();
}

However there are several users over at laravel suggesting to do the following:

/show/big-bang-theory-123/episode/01 where 123 is the item id of the show. Then I can simply do:

return Show::Find(123);

The question is, is the impact noticeable between these two and are there any future problems I might run into? Are there maybe other smarter method to have slugs in the URI?

In fact it's up to you how you will do it. If you plan to have data always from one table you may use only slug in url /show/big-bang-theory and as you see it will be enough to find it.

However if you wanted to use articles also from other tables, you need to add some unique part for them (for example /otherurls/big-bang-theory) because you don't want to make search in many tables.

So it's really up to you, I prefer not to include things I don't need in url. If I don't need id, I don't use it.

One quick way that I have handled this for blog posts is to route the id before the slug

Ex: /show/123/big-bang-theory/episode/01

This way you can also put any keywords in the slug as you want for seo purposes without messing up the routing or having to have a one to many table for all the possible slug routes.

  • /show/124/Doctor-Who/episode/01
  • /show/124/Doctor-Who(2005)/episode/01
  • /show/124/DrWho/episode/01

However, if you are just looking to optimize the query, Indexing is where the efficiency is at over dealing with an int/string. Never try and go out of your way to write bad code but at the same time do not go out of your way to optimize for efficiency until your application requires it. Unless there are clear performance issues your time is more valuable than clock cycles or disk IO.