Ad

Laravel : Create Hierarchical Route For Category

- 1 answer

I'm implementing category structure , some products would have one level category but other may have two or more level :

/posts/cat2/post-sulg

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

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

as i dont know how depth it would be and using category slugs is only for seo (i find post only by its slug) what is the best way to create a route to handle this structure?

Ad

Answer

You can solve this with:

Route::get('posts/{categories}', '[email protected]')
    ->where('categories','^[a-zA-Z0-9-_\/]+$');

And then in controller

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

}
Ad
source: stackoverflow.com
Ad