Laravel:为类别创建分层路由

ale*_*lex 2 seo categories multi-level laravel

我正在实施类别结构,一些产品将有一个级别类别,但其他产品可能有两个或更多级别:

/posts/cat2/post-sulg

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

/posts/cat-3/sub../../../post-slug
Run Code Online (Sandbox Code Playgroud)

因为我不知道它会有多深,并且使用类别slug仅适用于seo(我只发现它的slug)创建处理这种结构的路径的最佳方法是什么?

Fil*_*ski 8

你可以解决这个问题:

Route::get('posts/{categories}', 'PostController@categories')
    ->where('categories','^[a-zA-Z0-9-_\/]+$');
Run Code Online (Sandbox Code Playgroud)

然后在控制器中

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

}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但你应该添加` - > where('categories','^ [a-zA-Z0-9 -_\/] + $');`进行路由以使其工作 (2认同)