Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to route 2 parameters to a controller?

Tags:

This seems really basic but i can't get the hang of it.

I'm trying to send more then one parameter to a method in the controller, like this :

http://localhost/ci/index.php/subjects/3/state 

This is the routings i've tried :

$route['subjects/(:num)'] = 'subjects/view/$1'; $route['subjects/(:num)/{:any}'] = 'subjects/view/$1/$2'; 

the method accepted 2 paremeters :

public function view($slug, $id = null){  } 

but i seem to get a 404. How can i get this to work? i need the view method to always accept 1 parameter and optional other parameters.

NOTE : I am including the url helper.

like image 399
eric.itzhak Avatar asked Nov 06 '12 07:11

eric.itzhak


People also ask

How do I pass multiple parameters to a route?

Passing Multiple Parameters Using Route to Controller In this example, will first define a route with multiple parameters and then we will add a controller method accepting multiple parameters. Then we will setup a link with named route having multiple parameters.

What are the parameters of routing?

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req. params object, with the name of the route parameter specified in the path as their respective keys.

What is Route parameter in laravel?

Laravel routes are located in the app/Http/routes.A parameter provided in the route is usually annotated with curly braces. For instance, to pass in a name parameter to a route, it would look like this. By convention, the Controller function accepts parameters based on the parameters provided.


2 Answers

you have problem with your route brackets just change it from {} to () brackets will work

from

$route['subjects/(:num)/{:any}'] = 'subjects/view/$1/$2'; 

to

$route['subjects/(:num)/(:any)'] = 'subjects/view/$1/$2'; 
like image 188
umefarooq Avatar answered Oct 10 '22 03:10

umefarooq


Always maintain your routing rules

like

$route['subjects/(:num)/(:any)/(:any)/(:any)'] = 'subjects/view/$1/$2/$3/$4'; $route['subjects/(:num)/(:any)/(:any)'] = 'subjects/view/$1/$2/$3'; $route['subjects/(:num)/(:any)'] = 'subjects/view/$1/$2'; 

always follow this pattern for routing

if you add like this

$route['subjects/(:num)/(:any)'] = 'subjects/view/$1/$2'; $route['subjects/(:num)/(:any)/(:any)/(:any)'] = 'subjects/view/$1/$2/$3/$4'; $route['subjects/(:num)/(:any)/(:any)'] = 'subjects/view/$1/$2/$3'; 

then always first condition will be true every time.

also refer this link --> codeigniter routing rules

like image 42
PHP Team Avatar answered Oct 10 '22 02:10

PHP Team