RichardJeffery's avatar

Routes with unknown number of levels - Category hierarchy

I'm building a system that allows the user to create any number of categories and to nest them. The issue I've come across is how to build the routes for them. As an example I would like to use the following structure;

events/2020/football/premier-league/chelsea-vs-arsenal

Where 'events' is fixed, 'chelsea-vs-arsenal' is the actual event slug and the rest are categories.

As the categories are user controlled, I can't use a fixed number of URL parameters, unless I limit categories to a set number of levels which I'd rather avoid;

Route::get('events/{category}/{event:slug}', 'EventsController@show');
Route::get('events/{category}/{category}/{event:slug}', 'EventsController@show');
Route::get('events/{category}/{category}/{category}/{event:slug}', 'EventsController@show');

Has anyone come across this and a suitable solution before? Many thanks

0 likes
1 reply
RichardJeffery's avatar

Just a quick update, I decided to compromise slightly and opted for the following routes;

Route::get('categories', 'Controllers\Frontend\EventcategoriesController@index')->name('eventcategories.index');
Route::get('categories/{eventcategories}/event/{event}', 'Controllers\Frontend\EventsController@show')->where('eventcategories', '.*')->name('events.show');
Route::get('categories/{eventcategories}', 'Controllers\Frontend\EventcategoriesController@show')->where('eventcategories', '.*')->name('eventcategories.show');

It's important to have the more specific routes first before the more generic 'catch-all' route at the bottom. I can then explode the categories in the controller and perform any logic required to verify the URl structure is correct. IE the sub category belongs to the parent category etc.

Please or to participate in this conversation.