Reputation: 25
I would like to create a dynamic route that allows multiple segments.
example.com/segment1
example.com/segment1/segment2/
example.com/segment1/segment2/segment3
Using this:
Route::get('{slug}', 'PagesController@index');
Gives me my first dynamic segment and of course I could do this:
Route::get('{slug1}/{slug2}', 'PagesController@index');
and so on but I'm sure there's a better way to do this.
Upvotes: 1
Views: 1020
Reputation: 15566
I believe one complication when using Route::get('{slug1}/{slug2}', 'PagesController@index');
would be handling all possible inputs so segment1/segment2/
and also foo/bar/
. You would probably end up with lots of unnecessary logic.
This may not be the best solution but I believe groups would work well for what you are trying to accomplish.
Route::group(array('prefix' => 'segment1'), function() {
Route::get('/', 'ControllerOne@index');
Route::group(array('prefix' => 'segment2'), function() {
Route::get('/', 'ControllerTwo@index);
Route::get('/segment3', 'ControllerThree@index');
});
});
Maybe a little messy when only dealing with three examples but it could end up being beneficial and provide a nicer hierarchy to work with.
This also has the benefit for using before
and after
filters. Like for all segment2
endpoints if you want to perform some filter, instead of adding the filter to all the individual endpoints you can just add it to the group!
Route::group(array('before' => 'someFilter', 'prefix' => 'segment2'), function() {
// ... ...
});
Upvotes: 1