Laravel 5.2 带可选参数的路由
Laravel 5.2 Routing with optional params
我正在 Laravel 5.2 中创建一个简单的产品搜索引擎。我可以使用 get 或 post,无论哪个都能完成我想要的,即使我需要做一些后端处理然后将漂亮的 URL 传递给另一个方法来显示产品。
我的参数是
- 询问
- 商人
- 牌
- 页
- 排序
所有这些参数都可以单独使用或单独使用。
如果可能的话,我想使用漂亮的 URLs。
基本上我希望 URL 看起来像这样:
/shop/query/shoes
/shop/query/shoes/brand/nike
/shop/query/sort/price
/shop/merchant/amazon
这5个参数可以组成很多不同的路由,但都是可选的。那么什么是使这条路线按照我想要的方式工作的最佳解决方案,而不需要为每条可能的路线编码。
我确定我忽略了一些东西。我之前使用过 Zend Framework,只是在 shop 之后使用 * 然后我可以传递任何东西。
如果您需要任何其他信息,请告诉我。感谢您的帮助。
尝试这样的事情
Route::get('shop/{params?}', function(Request $request, $params = '') {
// everything after "shop/" will be in $params
// you need to add custom logic to parse and handle $params string
return $params;
})->where('params', '(([a-zA-Z0-9-_]+)\/?)+');
{params?} 是 Optional Parameter
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value
->其中('params', ...) 是 Regular Expression Constraint
You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained
注意
确保调整 (([a-zA-Z0-9-_]+)/?)+ 正则表达式以涵盖所有情况,因为这是我添加的用于快速测试您的示例的东西
我正在 Laravel 5.2 中创建一个简单的产品搜索引擎。我可以使用 get 或 post,无论哪个都能完成我想要的,即使我需要做一些后端处理然后将漂亮的 URL 传递给另一个方法来显示产品。
我的参数是 - 询问 - 商人 - 牌 - 页 - 排序
所有这些参数都可以单独使用或单独使用。 如果可能的话,我想使用漂亮的 URLs。
基本上我希望 URL 看起来像这样:
/shop/query/shoes
/shop/query/shoes/brand/nike
/shop/query/sort/price
/shop/merchant/amazon
这5个参数可以组成很多不同的路由,但都是可选的。那么什么是使这条路线按照我想要的方式工作的最佳解决方案,而不需要为每条可能的路线编码。
我确定我忽略了一些东西。我之前使用过 Zend Framework,只是在 shop 之后使用 * 然后我可以传递任何东西。
如果您需要任何其他信息,请告诉我。感谢您的帮助。
尝试这样的事情
Route::get('shop/{params?}', function(Request $request, $params = '') {
// everything after "shop/" will be in $params
// you need to add custom logic to parse and handle $params string
return $params;
})->where('params', '(([a-zA-Z0-9-_]+)\/?)+');
{params?} 是 Optional Parameter
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value
->其中('params', ...) 是 Regular Expression Constraint
You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained
注意
确保调整 (([a-zA-Z0-9-_]+)/?)+ 正则表达式以涵盖所有情况,因为这是我添加的用于快速测试您的示例的东西