我经常看到网站上有类别,子类别和文章的漂亮网址。如何使用Laravel复制此功能?
我需要使用以下路线:
/kb/{id (numeric)}
/kb/{category}
/kb/{category}/{article} (redirects to the route immediately below, adding the id)
/kb/{category}/{article}/{id (numeric)}
/kb/{category}/{subcategory}
/kb/{category}/{subcategory}/{article} (redirects to the route immediately below, adding the id)
/kb/{category}/{subcategory}/{article}/{id (numeric)}
/kb/download/{id (numeric)}
我还打算尝试将漂亮的URL包含在分页中,但我意识到它可能会使类别和子类别在/page/1
部分之后进一步复杂化,但是,如果您知道如何使其工作,请告诉我们!
目前,我的代码如下:
Route::group(['prefix' => '/kb', 'as' => 'kb::'], function () {
Route::get('/', function() {
echo "<h1>Index</h1>";
});
Route::get('{id}', function($id = null) {
echo "<h1>ID: $id</h1>";
})->where('id', '0-9+');
Route::get('download/{id}', function($id = null) {
echo "<h1>Download ID: $id</h1>";
})->where('id', '0-9+');
Route::get('{category}', function($category = null) {
echo "<h1>Category: $category</h1>";
});
Route::get('{category}/{article}', function($category = null, $article = null) {
echo "<h1>Category: $category</h1>";
echo "<h1>Article: $article</h1>";
});
Route::get('{category}/{article}/{id}', function($category = null, $article = null, $id = null) {
echo "<h1>Category: $category</h1>";
echo "<h1>Article: $article</h1>";
echo "<h1>ID: $id</h1>";
})->where('id', '0-9+');
Route::get('{category}/{subcategory}', function($category = null, $subcategory = null) {
echo "<h1>Category: $category</h1>";
echo "<h1>SubCategory: $subcategory</h1>";
});
Route::get('{category}/{subcategory}/{article}', function($category = null, $subcategory = null, $article = null) {
echo "<h1>Category: $category</h1>";
echo "<h1>SubCategory: $subcategory</h1>";
echo "<h1>Article: $article</h1>";
});
Route::get('{category}/{subcategory}/{article}/{id}', function($category = null, $subcategory = null, $article = null, $id = null) {
echo "<h1>Category: $category</h1>";
echo "<h1>SubCategory: $subcategory</h1>";
echo "<h1>Article: $article</h1>";
echo "<h1>ID: $id</h1>";
})->where('id', '0-9+');
});
不幸的是,这种习惯会混淆文章和子类别,并且总是很混乱。但我看到网站具有这种结构,甚至更复杂的结构,它们起作用 - 这是什么秘密?!
同样重要的是要记住,两个类别可能具有相同名称的子类别,这些子类别不是相同的子类别,这使事情变得更加复杂。
编辑:我刚刚看了一下可能会使每篇文章都以article
为前缀,例如/kb/cat/article/evil/666
。但是,似乎仍然没有正常工作,令人生气。