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 with is_unique
and if it isn't, alter it slightly and re-check until the validation passes. Even though form_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:
$slug = url_title($this->input->post('title'), 'dash', TRUE).strtotime(date('Y-m-d H:i:s'));
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)
$this->db->select('count(*) as slugcount');
$this->db->from('your_table');
$this->db->where('slug', $slug);
$query = $this->db->get();
return $query->row(0)->slugcount;
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
$slug = $slug."-".$slugcount;
would that work?