11

I'm trying to create a dynamic route for an unlimited number of URL levels.

Here's my current route

Route::get('{pageLink}', array('uses' => 'SiteController@getPage'));

This works for the first level. So a URL like something.com/foo/ would work. But if I had something like something.com/foo/bar/ it wouldn't catch that URL. I need it to match unlimited levels. That way in my controller it'll get me a variable of whatever the entire link is.

I know I could do

Route::get('{pageLink}', array('uses' => 'SiteController@getPage'));
Route::get('{pageLink}/{pageLink2}', array('uses' => 'SiteController@getPage'));
Route::get('{pageLink}/{pageLink2}/{pageLink3}', array('uses' => 'SiteController@getPage'));

But that just seems like an overkill. Is there a better way to do this so it'll match to the end of the URL?

Thanks.

tereško
  • 58,060
  • 25
  • 98
  • 150
David Maksimov
  • 369
  • 5
  • 17

2 Answers2

25

You can try something like this:

//routes.php
Route::get('{pageLink}/{otherLinks?}', 'SiteController@getPage')->where('otherLinks', '(.*)');

Remember to put the above on the very end (bottom) of routes.php file as it is like a 'catch all' route, so you have to have all the 'more specific' routes defined first.

//controller 
class SiteController extends BaseController {

    public function getPage($pageLink, $otherLinks = null)
    {
        if($otherLinks) 
        {
            $otherLinks = explode('/', $otherLinks);
            //do stuff 
        }
    }

}

This approach should let you use unlimited amount of params, so this is what you seem to need.

Gadoma
  • 6,475
  • 1
  • 31
  • 34
1

@Fusion https://laravel.com/docs/5.4/routing

You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained. so {id} is a route parameter , and ->where('id', '[0-9]+') is a regex expression for this parameter. If u need to use more than parameters you can do something like this :

Route::get('user/{id}/{id2}', function ($id) { })->where('id', '[0-9]+')->where('id2', '[[0-9]+]');


    Route::get('user/{id}', function ($id) {

    })->where('id', '[0-9]+');
Saqib Omer
  • 5,387
  • 7
  • 50
  • 71
  • 2
    Add comments and explain your answer. – Saqib Omer Mar 03 '17 at 12:30
  • You may constrain the format of your route parameters using the where method on a route instance. The where method accepts the name of the parameter and a regular expression defining how the parameter should be constrained. so {id} is a route parameter , and ->where('id', '[0-9]+') is a regex expression for this parameter. If u need to use more than parameters you can do something like this : Route::get('user/{id}/{id2}', function ($id) { })->where('id', '[0-9]+')->where('id2', '[[0-9]+]'); – Aleksei Odegov Mar 15 '17 at 09:43