How to set dynamic route to use slug in CodeIgniter?
codeigniter, php, url-rewriting, url-routing
Solution
Urls are routed in the following order:
- Explicit routes in `$route` (routes.php) are checked in order.
- An implicit route `[folder/]controller/methodname/args...` is attempted as a fallback.
If have a small number of known explicit routes, you can just add them to `$route`:
$route['(my-slug|my-other-slug|my-third-slug)'] = 'pages/slug_on_the_fly/$1'
(Routes keys are really parsed as regular expressions with `:any` and `:num` are rewritten to `.+` and `[0-9]+`.)
If you have a large number of such routes (probably not a good idea, BTW!) you can just add a wildcard route to the end of `$route`:
$route['([^/]+)/?'] = 'pages/slug_on_the_fly/$1'
The regex here means "any url that has no slashes (except maybe last)". You can refine this to describe your slug format if you have any other restrictions. (A good one is `[a-z0-9-]+`.) If your controller finds the slug in the db, you're done. If it doesn't, it must serve a 404.
However, you give up the possibility of some implicit routing as Codeigniter doesn't provide any way for a controller to "give up" a route back to the router. For example, if you have a controller named 'foo' and you want a url like `/foo` to route to `Foo::index()`, you must add an explicit route for this case because it would be caught by this route and sent to `Pages::slug_on_the_fly('foo')` instead. In general, you should not have slugs which are also controller class names! This is why you should have a very small number of these url-slugs, if you have any at all!
If you have both a large number of these explicit routes and you are not willing to abide by these implicit routing limitations, you can try adding them to `$route` dynamically:
- Make a `routes_extra.php` file which `routes.php` includes at the end. Write new routes to it as part of saving a page or when you build/deploy the site.
- Subclass `Router.php` and add a new routing layer.
- Add a `pre_system` hook which adds the routes.
I'm sure there are other ways.
Problem
Let's say that I have a controller named pages and there is a method slug_on_the_fly `public function slug_on_the_fly($slug)` How would my route for this look like? E.g. for blog controller it would be easy: ``` $route['blog/(:any)'] = 'pages/slug_on_the_fly/$1'; ``` and then `http://localhost/blog/name-of-the-article` works nice However, what if I want to do it like without `blog` so e.g. `http://localhost/name-of-the-article` or `http://localhost/another-article-blablabla` How to do it and don't break another routes e.g. `$route['friends'] = 'users';` or `$route['about-us'] = 'pages/about_us';` ? Because if I do: `$route['(:any)'] = 'pages/slug_on_the_fly/$1';` It will probably ruin everything else or?