Laravel路由到错误的控制器方法

时间:2017-07-12 08:23:27

标签: php laravel routing laravel-5.4 laravel-routing

我有以下两条路线:

ROUTE1:

Route::get(config('api.basepath') . '{username}/{hash}/{object_id}', [
    'action' => 'getObject',
    'uses' => 'ObjectController@getObject',
]);

Route2到:

Route::get(config('api.basepath') . 'object-boxes/{object_id}/boxes', function () {
    if (Input::get('action') == 'filter') {
        return App::call('App\Http\Controllers\FilterController@getFilteredContents');
    } else {
        return App::call('App\Http\Controllers\ObjectBoxController@show');
    }
});

现在,

路由1可用或不带Auth中间件,而Route2在Auth中间件下。

但是,在任一调用中,执行控制都将转到ObjectController @ getObject

当我在Route2下面移动Route1时,每次调用到ObjectBoxController @ show。

我试过Preceed但没有改变。 我应该如何解决这个问题

2 个答案:

答案 0 :(得分:4)

您的第一条和第二条路线相似,

第一条路线

config('api.basepath') . '{username}/{hash}/{object_id}'

第二条路线

config('api.basepath') . 'object-boxes/{object_id}/boxes'

当你有第二个路线的情况时,它被视为前一个路线,并将username作为object-boxesobject_id作为boxes。因此,两种情况都需要相同的功能。因此,尝试使用这两种路线的不同路线模式。

答案 1 :(得分:2)

您应该定义路线中的变量,而不是每条路线末尾的where

Route::get(config('api.basepath') . '{username}/{hash}/{object_id}', [
    'action' => 'getObject',
    'uses' => 'ObjectController@getObject',
])->where('object_id', '[0-9]+');

Route::get(config('api.basepath') . 'object-boxes/{object_id}/boxes', function () {
    if (Input::get('action') == 'filter') {
        return App::call('App\Http\Controllers\FilterController@getFilteredContents');
    } else {
        return App::call('App\Http\Controllers\ObjectBoxController@show');
    }
})->where('object_id', '[0-9]+');
  

您可以使用路由实例上的where方法约束路由参数的格式。 where方法接受参数的名称和定义参数应该如何约束的正则表达式:

here