Laravel 路由混淆了 id 和 slug

Laravel route got confuse about id and slug

我的项目中有一条如下所示的路线:

    Route::get('/product/{category}/{all}/{name}-{id}.html', ['as' => 'product.single', 'uses' => 'ProductController@single'])->where('id', '[0-9]+');

所以这就是问题所在,作为传统,我们将 slug 放在 url(然后是 id),但这样我们的一些路由会在 id 部分混淆,这是一个例子: /product/gold/women-gold/one-special-167.html 因为 url laravel 中的 ((-)) 认为 special-167 是 id,尽管它不是。 那么有什么合理的方法可以解决这个问题吗?

请尝试为名称启用 - 字符

 Route::get('/product/{category}/{all}/{name}-{id}.html', ['as' => 'product.single', 'uses' => 'ProductController@single'])->where(['id' => '[0-9]+','name' => '[a-zA-Z-]+']);

首先将 {id}(然后是 {name})同时放入您的路线和方法中:

Route::get('/product/{category}/{all}/**{id}**-**{name}**.html', ['as' => 'product.single', 'uses' => 'ProductController@single'])->where('id', '[0-9]+');

你可以很容易地替换路由中的id和name或者将它们分开/