简体   繁体   中英

How can I add url extensions to laravel routes with optional parameters?

I have the following routes for a webshop with categories and products:

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 is a subcategory of categoryOne

categoryThree is a subcategory of categoryTwo

This works perfect but I need to put .html at the end so the url's are exactly the same as the url's from the old webshop.

For the productpage this is no problem:

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

If I do this for the category page it doesn't work when the optional parameters are not filled.

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

This results in: domain.com/c/category1//.html

Any ideas on how to solve this so I get:

domain.com/c/category1.html

domain.com/c/category1/category2.html

domain.com/c/category1/category2/category3.html

You have two options:

  1. Use category2 and category3 as query parameters, after .html , and pass them as ?category2=aaa&category3=bbb ;
  2. Define multiple routes under the same group as follows (see next code example). I don't like this solution but it should work if you call the routes correctly and not from the 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')
    });

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