【问题标题】:How to make a route with different controllers and the same URL's with laravel 4?如何使用 laravel 4 使用不同的控制器和相同的 URL 创建路由?
【发布时间】:2015-09-15 05:35:38
【问题描述】:

我的视图 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() 函数。

【问题讨论】:

    标签: php laravel laravel-4 routes


    【解决方案1】:

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

    将路线更改为:

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

    【讨论】:

      【解决方案2】:

      问题是,不管你叫什么......

      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
          }
      }
      

      【讨论】:

      • 谢谢!我还通过将这些用作路线来解决此问题:
      • Route::get('/game/{itemId}_first', array('as' => 'checkFirstName', 'uses' => 'GameController@checkFirstName')); Route::get('/game/{itemId}_second', array('as' => 'checkSecondName', 'uses' => 'GameController@checkSecondName'));
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2017-04-05
        • 1970-01-01
        • 2013-09-24
        • 2016-03-29
        • 2021-11-05
        • 1970-01-01
        • 2018-09-10
        • 2016-10-03
        • 1970-01-01
        相关资源
        最近更新 更多