If keeping your urls in a valid hierarchy is important, then you can probably do a check like so:
Route::get('category/{hierarchy}', function($hierarchy)
{
$categories = explode('/', $hierarchy);
$main = Category::where('slug', end($categories))->first();
reset($categories);
if ($main)
{
$ancestors = $main->getAncestors();
$valid = true;
foreach ($ancestors as $i => $category)
{
if ($category->slug !== $categories[$i])
{
$valid = false;
break;
}
}
if ($valid)
{
/* continue on with your code here... */
}
}
App::abort('404');
})->where('hierarchy', '(.*)?');
If keeping the parent categories isn't important,then you can get rid of most of the above code, and instead just grab the end of $categories and use that end slug as you would normally.
Then you have to implode the ancestors on your URLs using '/' as the glue. Like so:
<a href="/category/'.implode('/', $category->getAncestorsAndSelf()->lists('slug')).'">link</a>
You could always split the slug field into two:
slugs: parent1-slug/parent2-slug/child-slug slug: child-slug
That should work, i'll test it later and let you know. Thanks for your response.
There is no point doing that, you can just do this...
Route::get('test/{one}/{two}', function($one, $two)
{
return 'two: ' . $one . ', ' . $two;
});
Route::get('test/{one}', function($one)
{
return 'one: ' . $one;
});
I'm sorry @ConnorVG, but @andrewsuzuki-s version was exactly what I was looking for.
Yea, ConnerVG's solution means manually determining the full depth. The initial solution should "just work" no matter the number of children (which in some cases can be quite heavy.)
Oh, I see... I didn't noticed you wished for more than just 1 child. Sorry bud!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community