简体   繁体   中英

Wildcard URL routing in Laravel

I am attempting to create a set of routes in laravel. The first two are simple.

/ loads home
/12345 loads a result for 12345 via ResultController, which I accomplished with {result}/ .

The third route I would like is /12345/foo/bar/baz, which eventually will execute a second controller that presents files. Basically /foo/bar/baz represents the file location, so it could be any level of depth. I would like to pass it to the controller as a single value. I tried the below route to simply test that it would work:

Route::get('/', function()
{
    return View::make('home.main');
});
Route::get('{result}/', 'ResultController@showResult');
Route::get('{result}/(.*)', function() {
    return 'Huzzah!';
});

Currently, going to any path below {result}/ is still resulting in a 404. For example:

/12345/foo -> Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException

You may try something like this but probably not a very good solution:

Other route declaration
Route::get('')

// At the bottom
Route::get('{result}/{any?}', function($result, $any = null) {

    // $any is optional
    if($any) {
        $paramsArray = explode('/', $any);
        // Use $paramsArray array for other parameters
    }

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

Be careful, it can catch any URL that matches with this. Put this at the bottom of all routes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM