如何使用不同的控制器和相同的 URL 与 laravel 4 创建路由?

How to make a route with different controllers and the same URL's with laravel 4?

我有这些链接 game.blade.php :

<a href="{{ URL::route('checkFirstName', $item->PK_item_id) }}"></a> 

<a href="{{ URL::route('checkSecondName', $item->PK_item_id) }}"></a>  

这些路由在 mu routes.php 文件中:

Route::get('/game/{itemId}', array('as' => 'checkFirstName', 'uses' => 'GameController@checkFirstName'));
Route::get('/game/{itemId}', array('as' => 'checkSecondName', 'uses' => 'GameController@checkSecondName'));

以及我的 GameController.php 中的这些方法:

public function checkFirstName($itemId)
{
    dd('check first name from ' . $itemId);

}

public function checkSecondName($itemId)
{
    dd('check second name from ' . $itemId);

}

问题:

两个链接都指向 checkSecondName() 函数。

您的路由设计完全错误 - 您的两条路由匹配相同的路径,所以这里发生的是第二条覆盖了第一条。尝试使用不同的路径,或者如果两个控制器都提供相同的功能,则可以只使用一个控制器。 不能有两条不同的路由匹配同一条路径。

事实是,无论你打电话给...

URL::route('checkSecondName', $item->PK_item_id)

或...

URL::route('checkFirstName', $item->PK_item_id)

...Laravel 将生成 相同的 URL 路径 ,即 - /game/{itemId}。命名路由的存在是为了方便。最后重要的是Route声明中指定的路径。

所以,Laravel 会检查路径以找到匹配的路由,但在您的情况下有两个匹配项。最后一个是设计选择的。

这应该告诉你的是非常简单的:你不能让同一个路由调用不同的控制器方法。 可以 不同的是所使用的动词:Route::get('/game/{itemId}')Route::post('/game/{itemId}') 不同,但这只是旁注。

这里可以做的是,例如有一个额外的参数来确定要完成的操作类型:

路线

Route::get('/game/{itemId}/{type}', array('as' => 'checkName', 'uses' => 'GameController@checkName'));

HTML

<a href="{{ URL::route('checktName', ['itemId' => $item->PK_item_id, 'type' => 'first']) }}"></a> 

<a href="{{ URL::route('checktName', ['itemId' => $item->PK_item_id, 'type' => 'last']) }}"></a> 

控制器

public function checkName($itemId, $type)
{
    if ($type === 'first') {
        // first name handling        
    } else {
        // last name handling
    }
}

lessugar的回答是正确的。我还找到了另一种解决方案,所以我想我也应该在这里添加它。

将路线更改为:

Route::get('/game/{itemId}_first', array('as' => 'checkFirstName', 'uses' => 'GameController@checkFirstName'));
Route::get('/game/{itemId}_second', array('as' => 'checkSecondName', 'uses' => 'GameController@checkSecondName'));