Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create routes with unlimited sub-pages in Laravel?

Is there any way to capture unlimited levels of URLs of sub-pages. My application allows any user to create any level of sub-pages. In my pages table I have parentID.

/{page}/{subpage} // this captures 2 level of pages
/{page} // this captures 1 level of page

I want to capture all URLs ranging from

site.com/food/healthy/fruit/red/apple to site.com/fruit/organge or site.com/grapes or site.com/a/b/c/d/e/f/g/h/i/j and so on.

what would be the most efficient way?

like image 830
Navi Avatar asked Dec 14 '25 01:12

Navi


1 Answers

Sure it's possible. You'd need to explode the captured pages on the slash / and go from there though.

Route::any('{any}', function($pages)
{
    $pages = explode('/', $pages);

    // Do whatever...
})->where('any', '.*');

A few things to be aware of:

  1. This route should be placed last, otherwise you won't be able to hit any other routes.
  2. This captures absolutely everything, you'll need to return an error should the page not exist.
  3. I'm using Route::any in the above to capture any request (POST, GET, etc), you might want to limit this to a subset of those or only GET, that's up to you.
  4. As pointed out in the comments below, you can no longer use the URL::route helper but you can still make use of the URL::to helper. This shouldn't be a problem as it's more than likely you're storing these dynamic pages in a database and as such the URI should be stored within the database as well.
like image 76
Jason Lewis Avatar answered Dec 16 '25 20:12

Jason Lewis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!