In a recent Laravel project I needed a way to get pretty URLs BUT to ensure that they are unique. You might think, why not just set the column to UNIQUE in SQL? Simple, with a multi-tenant setup we needed it unique but only unique to the tenant but we also wanted it to auto-increment a counter at the end of the slug if there was already a slug like it.
For example, if you wanted to save the About Us page though you already have a About Me page with the slug “slug”, then you wouldn't be able to save the About Us page with the slug “/about” correct? With the code we have here it'll save the new page (or whichever page is being created/updated last) with “/about-<counter>” where the counter starts at 1. So in this example it would save it as “/about-1”.
This is a rather standard implementation of this idea. WordPress has had it for a long while now. A rather handy feature.
I've added the link to the GitHub code below. There are a few things to note though:
- The model is automatically chosen for you,
- the only thing you have to set is the default slug (pulled from a model attribute of your choice),
- It's assumed the attribute for your slug is ‘slug', but you can set that too,
- The first IF statement is a small extra safety check: if the value didn't update then don't run
Need Laravel Support, Help & Development?
If you liked this free GIST code, feel free to connect with me to get help on your projects. I offer hourly, weekly, monthly retainer and project rates.