I'm currently working on a project with Codeigniter.
I have one controller called Cat
class Cat extends CI_Controller {
function __construct(){
parent::__construct();
}
function index($action){
// code here
}
}
and a route (in routes.php)
$route['cats/:any'] = 'cat/index/$1';
And that works if I use this URL for example: http://www.mywebsite.com/cats/display
Nevertheless, if the user changes the URL to http://www.mywebsite.com/cats/ it doesn't work anymore. Codeigniter writes: 404 Page Not Found - The page you requested was not found.
So my goal is to redirect him to http://www.mywebsite.com/cats/display by default if he is on the cats/ page
Do I need to do another route?
I tried
$route['cats'] = 'cat/display';
...but without success. Thank you for your help.
There are a few ways to do this:
You could provide $action with 'display' by default:
function index($action = 'display'){}
OR
You could have a condition to physically redirect them
function index($action = ''){
if(empty($action)){redirect('/cats/display');}
//OTher Code
}
OR
You need to provide routes for when there is nothing there:
$route['cats'] = 'cat/index/display'; //OR the next one
$route['cats'] = 'cat/index'; //This requires an function similar to the second option above
Also, if you are only having a specific number of options in you route (ie. 'display', 'edit', 'new'), it might be worth setting up your route like this:
$route['cats/([display|edit|new]+)'] = 'cat/index/$1';
Edit:
The last route you created:
$route['cats'] = 'cat/display';
is actually looking for function display()
in the controller rather than passing index the 'display' option
best way to use _remap function in your controller it will remap your url to specific method of controller
class Cat extends CI_Controller {
function __construct(){
parent::__construct();
}
function _remap($action)
{
switch ($action)
{
case 'display':
$this->display();
break;
default:
$this->index();
break;
}
}
function index($action){
// code here
}
function display(){
echo "i will display";
}
}
check remap in CI user guide