Suppose i have this db table schema:
id | article | slug
1 hey guys how are you? hey-guys-how-are-you?
I'm trying keeping my db route field unique
route is always the message field camelized like this this-is-a-title-but-now-is-a-route
so inserting the same route produce a db error of duplicated key
so which is a good practice to control and insert always unique routes?
thanks
Because you've tagged CodeIgniter, I would suggest pre-checking the value of the slug field, then increment the value if need be. The CI string helper has a increment_string
function that will take care of that for you.
increment_string()
Increments a string by appending a number to it or increasing the number. Useful for creating "copies" or a file or duplicating database content which has unique titles or slugs.
Usage example:
echo increment_string('file', '_'); // "file_1"
echo increment_string('file', '-', 2); // "file-2"
echo increment_string('file-4'); // "file-5"
So
this-is-a-route
becomes this-is-a-route-1
and
this-is-a-route-1
becomes this-is-a-route-2
etc.
You can make use of php's uniqid and perhaps with more entropy to do the job for you.
The return value of this function is always of same length. Using more entropy its 23 and 13 otherwise. So you can easily substr the slug to get actual thing whenever you want.
This method make a loop to increment the slug until it find an non unexistant one.
In your model:
public function create_slug($title) {
$this->ci->load->helper('string');
$this->ci->load->helper('url');
$i = 1;
$max = 10;
$slug = url_title($title, '-', TRUE);
while($i <= $max && ($exist = $this->db->where('slug', $slug)->count_all_results('posts')) != 0) {
$slug= increment_string($slug, '-');
$i++;
}
//max was reached and the last slug is not unique
if($i >= $max && $exist > 0) return FALSE;
return $slug;
}