我使用laravel 7并将以下树结构存储在数据库中:
目录表:
category1
--category11
--category12
----category121
----category122
--category13文章表:
news
--news1
--news2Вasic Laravel路由如下所示:
Route::get('category/{id}', 'categoryController@show');
Route::get('news/{id}', 'newsController@show');但是在这种情况下,对于每个目录的URL,“类别”URL的片段是必需的,而对于每个新的URL,“新闻”URL的片段是必需的
如何使用Laravel路由来路由以下urls:
http://sitename.com/category1
http://sitename.com/category1/category11
http://sitename.com/category1/category12/category121
http://sitename.com/news
http://sitename.com/news/news1发布于 2020-05-18 18:04:14
您将需要一个“全部捕获”路由(如果您希望所有路径都是可配置的,则在所有其他路由之后注册)。
然后你可以在斜杠上分解路径,检查每个元素都是一个有效的类别段塞,并且也是前一个类别的子元素。
// All other routes...
Route::get('/{category_path}', 'CategoryController@show')->where('category_path', '.*');您也可以使用自定义路由绑定来完成此操作:
Route::bind('category_path', function ($path) {
$slugs = explode('/', $path);
// Look up all categories and key by slug for easy look-up
$categories = Category::whereIn('slug', $slugs)->get()->keyBy('slug');
$parent = null;
foreach ($slugs as $slug) {
$category = $categories->get($slug);
// Category with slug does not exist
if (! $category) {
throw (new ModelNotFoundException)->setModel(Category::class);
}
// Check this category is child of previous category
if ($parent && $category->parent_id != $parent->getKey()) {
// Throw 404 if this category is not child of previous one
abort(404);
}
// Set $parent to this category for next iteration in loop
$parent = $category;
}
// All categories exist and are in correct hierarchy
// Return last category as route binding
return $category;
});然后,您的类别控制器将接收路径中的最后一个类别:
class CategoryController extends Controller
{
public function show(Category $category)
{
// Given a URI like /clothing/shoes,
// $category would be the one with slug = shoes
}
}https://stackoverflow.com/questions/61866831
复制相似问题