Skip to content
Advertisement

How to route the URI with parameters to a method in codeigniter?

I don’t know much about the routing concept in codeigniter, I want to pass many parameters to a single method as explained in this http://www.codeigniter.com/userguide2/general/controllers.html tutorial page.

In the url I have this

http://localhost/code_igniter/products/display/2/3/4

In my routes.php I have written

$route['products/display/(:any)'] = 'Products_controller/display';

What I thought is it will pass all the parameters (here 2/3/4) to the method ‘display’ automatically but I am getting 404 page not found error.

In general I want to achieve something like, if the URI is controller/method I want to route to someother_controller/its_method and pass the parameters if any to that method. How can I do it?

Advertisement

Answer

In CI 3.x the (:any) parameter matches only a single URI segment. So for example:

$route['method/(:any)/(:any)'] = 'controller/method/$1/$2';

will match exactly two segments and pass them appropriately. If you want to match 1 or 2 you can do this (in order):

$route['method/(:any)/(:any)'] = 'controller/method/$1/$2';
$route['method/(:any)'] = 'controller/method/$1';

You can pass multiple segments with the (.+) parameter like this:

$route['method/(.+)'] = 'controller/method/$1';

In that case the $1 will contain everything past method/. In general I think its discouraged to use this since you should know what is being passed and handle it appropriately but there are times (.+) comes in handy. For example if you don’t know how many parameters are being passed this will allow you to capture all of them. Also remember, you can set default parameters in your methods like this:

public function method($param=''){}

So that if nothing is passed, you still have a valid value.

You can also pass to your index method like this:

$route['method/(:any)/(:any)'] = 'controller/method/index/$1/$2';
$route['method/(:any)'] = 'controller/method/index/$1';

Obviously these are just examples. You can also include folders and more complex routing but that should get you started.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement