I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4. The posts
table has a slug
column that I intend to use at making SEO friendly URLs.
Because every individual post’s slug will be a part of it’s URL, the slug
column is, of course, unique. I use CI’s url_title()
method to make the slug out of the post title:
$slug = url_title($this->input->post('title'), 'dash', TRUE);
Given the above described situation, it is obvious that a problem appears when 2 posts have the exact same title (“Who loves a butterfly?”):
Duplicate entry 'who-loves-a-butterfly' for key 'slug'
I need a way to make the duplicate title post generate a “numbered” slug: “who-loves-a-butterfly-1” and so on, if necessary.
The Codeigniter 3 documentation does not provide such a way for its url_title()
method? Is there a way I could modify it or an alternative to it?
4
Answers
Here is the full solution applied in my blog application:
In the Posts_model model:
In the Posts controller:
I’m using a custom function sanitize() – normally in a model – to create that unique slug entry:
please read code comment as it documents the flow
There’s a lot of creative approaches you could use. It all depends on your personal preference.
The first one, with query builder enabled would be to use the built-in
form_validation
and check if your slug complies withis_unique
and if it isn’t, alter it slightly and re-check until the validation passes. Even thoughform_validation
is used mainly to validate and sanitize user input, you can use it for pretty much anything.Another approach would be to always make sure you’re getting a unique slug on the first try by appending a nonce or a random number or some other unique parameter to the generated slug before insertion. For example:
The above, which is probably the simplest approach possible, will work as long as no two posts with exactly the same title are created at the exact same second. That would reduce the chance of collisions (almost) entirely.
A third solution, a little bit more cumbersome, would involve calculating the base slug with
$slug = url_title($this->input->post('title'), 'dash', TRUE);
and then:1.- pass the slug to a simple database query (either right there in the controller or inside a model, your choice)
If the slug is truly unique, you’ll be returned 0, if there’s one previous entry you’ll be returned 1 and so on.
Afterwards you choose:
The first time you create a slug, append a “-0” or a “-1” (depending on what’s best for SEO)
The second time you append a “-1” or a “-2” (depending on what you defined in the previous one)
and so on and so on
So, for example, you would alter your slug with
would that work?
This is a function which will create always unique slug for any table.
In Model
In Controller