将多个选项解析为路由条件

时间:2018-10-16 07:07:11

标签: php laravel

我有一个实例,希望将多种变体解析为一个视图。有没有一种方法可以在不重复执行路由功能的情况下实现?

示例:

Route::group(['prefix' => 'tools'], function () {
    Route::any('', function () {
        return View::make("tools.profile");
    });
    Route::any('/', function () {
        return View::make("tools.profile");
    });
    Route::any('view', function () {
        return View::make("tools.profile");
    });
    Route::any('view/{id}', 'Tools@profileUpdate', function ($id) {});
});

在上面的示例中,我希望''/view解析为查看View::make("tools.profile")

选项下方是否有类似的东西,可以在其中解析数组?

Route::group(['prefix' => 'tools'], function () {
    Route::any(['','/','view'], function () {
        return View::make("tools.profile");
    });
    Route::any('view/{id}', 'Tools@profileUpdate', function ($id) {});
});

3 个答案:

答案 0 :(得分:0)

我认为这对您有帮助

Route::group(['prefix' => 'tools'], function () {
    Route::get('/{name}',function(){
        return View::make("tools.profile");
    })->where('name', '|/|view');
    Route::any('view/{id}', 'Tools@profileUpdate', function ($id) {});
});

答案 1 :(得分:0)

是的,您可以按数组进行操作

$routes = array('','/','view');
foreach ($routes as $route) {
    Route::get($route, function () {
        return view('tools.profile');
    });
}

如果您想通过route(viewname),请使用closures

$routes = array('','/','view');
foreach ($routes as $route) {
    Route::get($route, function () use ($route) {
        info("view name ".$route);
        return view('tools.profile');
    });
}

答案 2 :(得分:0)

是的,您只需投资您正在做的事情:

Route::group(['prefix' => 'tools'], function () {
    Route::get('view/{id}', 'Tools@profileUpdate');
    Route::get('{x}', function ($x) {
        return view("tools.profile");
    });
});

如果您想提高安全性:

Route::group(['prefix' => 'tools'], function () {
        Route::get('view/{id}', 'Tools@profileUpdate');
        Route::get('{x}', function ($x) {
            if($x == '' || $x == '/' || $x == 'view'){
            return view("tools.profile");
            }else{
               /*Redirect to some where or make a error view or someting*/
            }
        });
    });