Laravel : 为类别创建分层路由
Laravel : create hierarchical route for category
我正在实施类别结构,有些产品会有一级类别,但其他产品可能有两级或更多级别:
/posts/cat2/post-sulg
/posts/cat-1/sub-1/post-slug
/posts/cat-3/sub../../../post-slug
因为我不知道它会有多深并且使用类别 slugs 仅适用于 seo(我发现 post 仅通过它的 slug)创建处理此结构的路由的最佳方法是什么?
您可以通过以下方式解决此问题:
Route::get('posts/{categories}', 'PostController@categories')
->where('categories','^[a-zA-Z0-9-_\/]+$');
然后在控制器中
class PostController
{
public function categories($categories)
{
$categories = explode('/', $categories);
$postSlug = array_pop($categories)
// here you can manage the categories in $categories array and slug of the post in $postSlug
(...)
}
}
我做了类似的事情,在 PostController.php 中使用
public function slug($slug) { return $this->show(Post::where('slug', @end(explode('/', $slug)))->firstOrFail()); }
在routes/web.php
Route::get ('posts/{slug}', 'PostController@slug')->name('post.slug')->where(['slug' => '^(?!((.*/edit$)|(create$))).*\D+.*$']);
Route::resource('posts', 'PostController');
如果要使用完整类别列表作为 slug,只需更改 slug 函数:
public function slug($slug) { return $this->show(Post::where('slug', $slug)->firstOrFail()); }
我正在实施类别结构,有些产品会有一级类别,但其他产品可能有两级或更多级别:
/posts/cat2/post-sulg
/posts/cat-1/sub-1/post-slug
/posts/cat-3/sub../../../post-slug
因为我不知道它会有多深并且使用类别 slugs 仅适用于 seo(我发现 post 仅通过它的 slug)创建处理此结构的路由的最佳方法是什么?
您可以通过以下方式解决此问题:
Route::get('posts/{categories}', 'PostController@categories')
->where('categories','^[a-zA-Z0-9-_\/]+$');
然后在控制器中
class PostController
{
public function categories($categories)
{
$categories = explode('/', $categories);
$postSlug = array_pop($categories)
// here you can manage the categories in $categories array and slug of the post in $postSlug
(...)
}
}
我做了类似的事情,在 PostController.php 中使用
public function slug($slug) { return $this->show(Post::where('slug', @end(explode('/', $slug)))->firstOrFail()); }
在routes/web.php
Route::get ('posts/{slug}', 'PostController@slug')->name('post.slug')->where(['slug' => '^(?!((.*/edit$)|(create$))).*\D+.*$']);
Route::resource('posts', 'PostController');
如果要使用完整类别列表作为 slug,只需更改 slug 函数:
public function slug($slug) { return $this->show(Post::where('slug', $slug)->firstOrFail()); }