Question

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.

Was it helpful?

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.

OTHER TIPS

I did the similar thing for my blog. @Varun As per Sachin's comment this is underline routing path domain.com/articles/view/ actually you will see url as domain.com/ as expected.

Also I have extended for Level Urls like this

$route['spring/(:any)'] = "controller_name/method_name/$1";
$route['hibernate/(:any)'] = "controller_name/method_name/$1";

So actual URL look like this

domainname.com/spring/spring-jdbc-example which is mapped to  "controller_name/method_name/$1"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top