Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel : create hierarchical route for category

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?

like image 287
alex Avatar asked Dec 19 '22 11:12

alex


1 Answers

You can solve this with:

Route::get('posts/{categories}', 'PostController@categories')
    ->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
        (...)
    }

}
like image 145
Filip Koblański Avatar answered Dec 26 '22 22:12

Filip Koblański