Wildcard URL routing in Laravel

瘦欲@ 提交于 2021-01-27 19:14:24

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/26227652/wildcard-url-routing-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!