Laravel 5.5 passing controllers to routes groups

时间:2017-04-10 02:01:38

标签: php laravel-routing laravel-5.4

I don't know if this is possible. Let's say we have 3 route groups to create the prefixes...all coming off of root; so, something like the following could be problematic.

Route::group([
        'prefix' => '{something}',
        'middleware' => ['web', 'auth']
    ], function() {
});

So, there are n route groups. Each group has the same set of route patterns. The only difference is the controller that is used for each group.

<?php

Route::group([
        'prefix' => 'prefix1',
        'middleware' => ['web', 'auth']
    ], function() {
    $controller = '\Path\To\Controller';
    Route::get('/', $controller.'@index');
    Route::get('/{object}', $controller.'@handleObject');
});

Route::group([
        'prefix' => 'prefix2',
        'middleware' => ['web', 'auth']
    ], function() {
    $controller = '\Path\To\Controller2';
    Route::get('/', $controller.'@index');
    Route::get('/{object}', $controller.'@handleObject');
});

Route::group([
        'prefix' => 'prefix3',
        'middleware' => ['web', 'auth']
    ], function() {
    $controller = '\Path\To\Controller3';
    Route::get('/', $controller.'@index');
    Route::get('/{object}', $controller.'@handleObject');
});

What I'm looking for is something that would allow me to go from the route group to something else, passing the controller to it.

Is this possible? Is there an alternative that I'm missing?

Essentially the route groups consist of multiple sub-groups and routes and really, really do not want to have to essentially copy and paste the routes only to change the controllers.

Update

Almost looking to be able to something like this, which I and pretty sure cannot be done.

Route::group([
        'prefix' => ['prefix1', 'prefix2', 'prefix3'],
        'middleware' => ['web', 'auth']
    ], function() {
    $controller = null;
    if ($prefix == '...') {
        $controller = '\Path\To\Controller3';

    } else if ($prefix '...') {
        ...

    }
    Route::get('/', $controller.'@index');
    Route::get('/{object}', $controller.'@handleObject');
});

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。

你只需要一个数组和逻辑。对于下面的示例,我在我开发的服务提供商中使用配置文件。然后,只需循环遍历数组,Laravel的路由器每次都会这样做。

// /config/service-config.php
$prefixes = [
    'tiles',
    'files',
    'kites',
    'foos'
];

// web.php
$controller = '\Path\To\Controller';

if (!is_null(config('service-config.prefixes'))) {
    foreach (config('service-config.prefixes') as $prefix) {    
        Route::group([
            'prefix' => $prefix
        ], function() use ($controller) {
            Route::post('/', $controller.'@addEmailAddress');
        });

        Route::group([
            'prefix' => $prefix .'/{foo}/bar'
        ], function() use ($controller) {
            // ...
        });
    }    
}

结果:

/tiles
/tiles/{foo}/bar
/files
/files/{foo}/bar
/kites
/kites/{foo}/bar
/foos
/foos/{foo}/bar

每个在该控制器中使用相同的控制器和方法。