Fra*_*ona 3 php laravel laravel-routing laravel-5
我想在搜索时生成这样的SEO友好URL:
http://www.example.com/search(无过滤器)
http://**www.example.com/search/region-filter
http://**www.example.com/search/region-filter/city-filter
并以这种方式对它们进行分页:
http://www.example.com/search/2(无过滤器,第2页)
http://**www.example.com/search/region-filter/2
http:/ /**www.example.com/search/region-filter/city-filter/2
(抱歉,由于声誉我不能发布2个以上的链接)
因此第二段可以是过滤器或多个页面(与第三个段相同).
我的Laravel 5路由文件:
Route::pattern('page', '[0-9]+');
...
Route::get('search/{region}/{city}/{page?}', 'SearchController@index');
Route::get('search/{region}/{page?}', 'SearchController@index');
Route::get('search/{page?}', 'SearchController@index');
Run Code Online (Sandbox Code Playgroud)
由于"页面"模式,路由工作正常,但在控制器内部这个请求http://**www.example.com/search/2映射$ page中的{page}(即使使用最后的路由规则):
public function index($region='', $city='', $page='')
Run Code Online (Sandbox Code Playgroud)
Codeigniter参数按名称映射,但看起来Laravel按位置映射它们,所以我总是得到$ region中的第一个.
是否可以通过名称而不是位置来路由参数,或者使用一些Laravel替代方法将它们放入控制器中?(我可以计算细分,但对我来说这是一个难看的解决方案)
您可以使用该Route::current()
方法访问当前路由并通过名称获取参数parameter method
.但是,您的路径定义存在问题,这会使最后两条路线定义无用.
因为page
最后两个路由中的参数是可选的,因为路由路径将使您的第二个和第三个路由不能正确匹配,因为路由的定义不明确.下面是测试用例,证明了我的观点.
如果你在控制器中有这个:
public function index()
{
$route = \Route::current();
$region = $route->parameter('region');
$city = $route->parameter('city');
$page = $route->parameter('page');
$params = [
'region' => $region,
'city' => $city,
'page' => $page
];
return $params;
}
Run Code Online (Sandbox Code Playgroud)
您将获得每条路线的以下结果:
1.对于example.com/search/myregion/mycity/mypage
:
{
"region": "myregion",
"city": "mycity",
"page": "mypage"
}
Run Code Online (Sandbox Code Playgroud)
2.对于example.com/search/myregion/mypage
:
{
"region": "myregion",
"city": "mypage",
"page": null
}
Run Code Online (Sandbox Code Playgroud)
3.对于example.com/search/mypage
:
{
"region": "mypage",
"city": null,
"page": null
}
Run Code Online (Sandbox Code Playgroud)
所以你的问题不在于按顺序或按名称进行参数匹配,而是与路径定义有关.要解决这个问题,您可以在查询字符串中添加分页并将其完全删除路由定义,因为如果它是可选的,那么将您的分页作为查询字符串参数绝对没有错.所以你的URL看起来像这样:
example.com/search/myregion/mycity?page=2
Run Code Online (Sandbox Code Playgroud)
您可以检查Illuminate\Routing\Route类API以查看您可以使用的其他方法.
归档时间: |
|
查看次数: |
3417 次 |
最近记录: |