Reputation: 18029
I have heard of people using slugs for generating clean urls. I have no idea how it works. Currently i have a codeigniter site which generates url's like this
www.site.com/index.php/blog/view/7
From what i understand by maintaining a slug field it is possible to achieve urls like
www.site.com/index.php/blog/view/once-upon-a-time
How is this done? Especially in reference to codeigniter?
Upvotes: 16
Views: 56270
Reputation: 1
Try to use this package: https://github.com/sawastacks/ci4-slugify
First, import this slugify class on controller:
use SawaStacks\CodeIgniter\Slugify;
You can get slugs as follow:
$post = new Post();
$title = 'André & François won mathematics competion';
$slug = Slugify::table('posts')->make($title); //When you use table name
$slug = Slugify::model(Post::class)->make($title); //When you use model object
On Updating record stage, do like this:
public function update_post(){
$id = $request->getVar('post_id');
$post = new Post();
$title = 'André & François won mathematics competion';
$slug = Slugify::model(Post::class)->sid($id)->make($title);
}
Upvotes: 0
Reputation: 1132
To my ES friends, remove accented characters using this, from Text Helper:
$string = 'áéíóú ÁÉÍÓÚ';
$slug = url_title(convert_accented_characters($string), 'dash', true); //convert_accented_characters function will deal with the accented characters.
echo $slug; //aeiou-AEIOU
Upvotes: 3
Reputation: 724402
I just store the slugs in my database table, in a column called slug
, then find a post with the slug, like this:
public function view($slug)
{
$query = $this->db->get_where('posts', array('slug' => $slug), 1);
// Fetch the post row, display the post view, etc...
}
Also, to easily derive a slug from your post title, just use url_title()
of the URL helper:
// Use dashes to separate words;
// third param is true to change all letters to lowercase
$slug = url_title($title, 'dash', true);
A little bonus: you may wish to implement a unique key constraint to the slug
column, that ensures that each post has a unique slug so it's not ambiguous which post CodeIgniter should look for. Of course, you should probably be giving your posts unique titles in the first place, but putting that in place enforces the rule and prevents your application from screwing up.
Upvotes: 55