3

I have four routes on my picture gallery app. They all do the same: query the database and render pictures. The only difference between them is the order of the records. For example:

http://example.com/favorites : shows pics ordered by favorites http://example.com/random : shows pics ordered by random http://example.com/votes : shows pics ordered by votes http://example.com/views : shows pics ordered by views 

For this, I want to use ONE action in my gallery controller and pass the order as a parameter.

I know I can create this route:

Route::get('/{orderby}', 'GalleryController@showPics') 

Then get the parameter from the controller:

class GalleryController extends BaseController { public function showPics($orderby) { //query model ordering by $orderby and render the view } } 

The problem is I don't want to capture example.com/whatever, only those four specific routes.

Is it there a way to pass a parameter to a controller action from the route. Or, alternatively, to read the current accessed route from the controller?

1 Answer 1

13

You can add a parameter constraint to your route that limits the possible values with a regular expression as show below.

Route::get('/{orderby}', 'GalleryController@showPics') ->where('orderBy', 'favorite|random|vote|view'); 

And as you know, you will get those values in the mapped controller action:

public function showPics($orderby) { dd($orderby); // favorite, random, vote or view. } 

You can read more about parameter route constraint in the docs: http://laravel.com/docs/routing#route-parameters

Sign up to request clarification or add additional context in comments.

1 Comment

My particular problem was not passing a variable to the controller method as in: public function showPics($orderby) { .. }. I was trying to get the value of the variable indirectly within the method like so: Input::get('orderby'); and this didn't work. The way you set up the route, however, did work for me similarly as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.