Search code examples
codeignitercodeigniter-urlcodeigniter-routing

How to have url's like domain.com/<article-name> in CodeIgniter


I have a articles controller and a view function in it to show an individual article, so my url's are like

http://domain.com/articles/view/<article-id>/<article-title>

My code:

class Articles extends CI_Controller {  
   function view($id=NULL,$slug=""){
        //Code to fetch article details from DB by id
    }
}

How do it make my url's to look like http://domain.com/<article-title>

Thank You.


Solution

  • Define all the controllers in routes config addressing to their own methods. At the end of routes config add following rule --

    $route['(:any)']   = 'articles/view/$1';
    

    All the requests other than previously defined route will now be served by artcile/view controller method.

    Next part is create a mapping table that will map article titles to article ids. You can get article title with

    $this->uri->segment(1);
    

    in view function.

    Whenever article is updated with title, then update mapping table as well.