Laravel 4路线,参数数量不受限制

2022-01-08 00:00:00 php laravel laravel-routing laravel-4

我正在尝试为无限数量的 URL 级别创建动态路由.

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

这是我目前的路线

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

这适用于第一级.所以像 something.com/foo/这样的 URL 可以工作.但是,如果我有类似 something.com/foo/bar/的东西,它就不会捕获那个 URL.我需要它来匹配无限级别.这样,在我的控制器中,无论整个链接是什么,它都会给我一个变量.

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.

我知道我能做到

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

但这似乎有点矫枉过正.有没有更好的方法来做到这一点,让它匹配到 URL 的末尾?

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?

谢谢.

推荐答案

你可以试试这样的:

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

请记住将上述内容放在 routes.php 文件的最后(底部),因为它就像一条包罗万象"的路线,因此您必须首先定义所有更具体"的路线.

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.

相关文章