Laravel:为类别创建分层路径

人气:657 发布:2022-10-16 标签: seo laravel categories multi-level

问题描述

我正在实现类别结构,一些产品可能有一个级别的类别,但另一些产品可能有两个或两个以上的级别:

/posts/cat2/post-sulg

/posts/cat-1/sub-1/post-slug

/posts/cat-3/sub../../../post-slug

由于我不知道它会有多深,而且使用类别插件仅适用于SEO(我只能通过其插件找到帖子),创建处理这种结构的最佳方法是什么?

推荐答案

可以通过以下方式解决:

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
        (...)
    }

}

1,009