从控制器访问 Laravel 路由或从路由向控制器传递参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18208969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access Laravel route from controller or pass parameter to controller from route
提问by Agu Dondo
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.
问题是我不想捕获 example.com/whatever,只想捕获这四个特定路由。
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?
有没有办法将参数从路由传递给控制器操作。或者,或者,从控制器读取当前访问的路由?
回答by Rubens Mariuzzo
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
您可以在文档中阅读有关参数路由约束的更多信息:http: //laravel.com/docs/routing#route-parameters