如何使用可选参数将lal扩展名添加到laravel路由?

问题描述 投票:1回答:1

对于具有类别和产品的网上商店,我有以下路线:

Route::name('shop.products.view')->get('/p/{productUrl}', 'Shop\ProductsController@view');
Route::name('shop.categories.view')->get('/c/{categoryOne}/{categoryTwo?}/{categoryThree?}', 'Shop\CategoriesController@view')

categoryTwo是categoryOne的子类别

categoryThree是categoryTwo的子类别

这很完美,但我需要在最后放置.html,所以网址与旧网店的网址完全相同。

对于产品页面,这没有问题:

Route::name('shop.products.view')->get('/p/{productUrl}.html', 'Shop\ProductsController@view');

如果我为类别页面执行此操作,则在未填充可选参数时它不起作用。

Route::name('shop.categories.view')->get('/c/{categoryOne}/{categoryTwo?}/{categoryThree?}.html', 'Shop\CategoriesController@view')

这导致:domain.com/c/category1//.html

关于如何解决这个问题的任何想法,我得到:

domain.com/从/category1.HTML

domain.com/从/category1/category2.HTML

domain.com/从/category1/category2/category3.HTML

php laravel url-routing
1个回答
0
投票

您有两种选择:

  1. .html之后使用category2和category3作为查询参数,并将它们作为?category2=aaa&category3=bbb传递;
  2. 在同一组下定义多个路由,如下所示(请参阅下一个代码示例)。我不喜欢这个解决方案但是如果你正确地调用路由而不是来自url builder URL::action('Shop\CategoriesController@view')它应该可以工作。
    Route::name('shop.products.view.')->group(function () {
        Route::get('/c/{categoryOne}/{categoryTwo}/{categoryThree}.html', 'Shop\CategoriesController@view');
        Route::get('/c/{categoryOne}/{categoryTwo}.html', 'Shop\CategoriesController@view');
        Route::get('/c/{categoryOne}.html', 'Shop\CategoriesController@view')
    });
© www.soinside.com 2019 - 2024. All rights reserved.