Codeigniter blog application: avoid duplicate entry error for slug

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?

Leave a Reply

Your email address will not be published. Required fields are marked *