...
CodeIgniter, Tutorials

How to set dynamic route for slug in CodeIgniter ?

09 January 2019

In this post we are going to show how to set dynamic route of posts slug coming from datatabase in codeigniter.

Codeigniter posts url are dynamic generated from database data. But it can’t define static route in the url. So for that all dynamic routes define in route.php eith (:any) for any string in url. This route work on regex of url and redirect request to destination path.

Setting your own routing rules

Routing rules are defined in your application/config/routes.php file. In it you’ll see an array called $route that permits you to specify your own routing criteria. Routes can either be specified using wildcards or Regular Expressions.

Route file

$route[ 'post/(:any)' ] = 'pages/get_post/$1';

//If post id is passed in url
$route['post/(:num)'] = 'post/get_post/$1';

//or you can define each post url here by using below code
require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$query = $db->get( 'posts' );
$result = $query->result();
foreach( $result as $row )
{
    $route[ 'post/'.$row->slug ] = 'post/get_post/$1;
}

After that check link http://localhost/post/name-of-the-article works perfectly. This request get post detail from post controller’s get_post function and retrieve data from database to view file.

In conclusion, you can set dynamic route of posts slugs in codeigniter routes.

Leave a Comments