简体   繁体   中英

Access Laravel route from controller or pass parameter to controller from route

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM