Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using slugs in codeigniter

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?

like image 506
esafwan Avatar asked Jul 22 '10 04:07

esafwan


People also ask

How to get slug from url in codeigniter?

The following function converts a string into a slug: $this->load->helper('text'); $this->load->helper('url'); $slug = url_title(convert_accented_characters($string), 'dash', true); However, this functions does not fully support transliteration for foreign languages, especially french.

What is a slug in PHP?

A slug is a human-readable, unique identifier, used to identify a resource instead of a less human-readable identifier like an id .


2 Answers

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.

like image 103
BoltClock Avatar answered Sep 20 '22 03:09

BoltClock


To my ES friends, remove accented characters using this, from Text Helper:

    $string = 'áéíóú ÁÉÍÓÚ';    
    $slug = url_title(convert_accented_characters($string), 'dash', true));
    echo $slug; //aeiou-AEIOU
like image 45
Italo Hernández Avatar answered Sep 20 '22 03:09

Italo Hernández