如何使用laravel 4使用不同的控制器和相同的URL进行路由? [英] How to make a route with different controllers and the same URL's with laravel 4?
问题描述
我的游戏game.blade.php中有这些链接:
I have these links in my view game.blade.php :
<a href="{{ URL::route('checkFirstName', $item->PK_item_id) }}"></a>
<a href="{{ URL::route('checkSecondName', $item->PK_item_id) }}"></a>
这些路线在mu route.php文件中:
And these routes in mu routes.php file :
Route::get('/game/{itemId}', array('as' => 'checkFirstName', 'uses' => 'GameController@checkFirstName'));
Route::get('/game/{itemId}', array('as' => 'checkSecondName', 'uses' => 'GameController@checkSecondName'));
和我GameController.php中的这些方法:
and these methods in my GameController.php :
public function checkFirstName($itemId)
{
dd('check first name from ' . $itemId);
}
public function checkSecondName($itemId)
{
dd('check second name from ' . $itemId);
}
问题:
两个链接都将转到checkSecondName()函数.
Both links are going to the checkSecondName() function.
推荐答案
事实就是如此,您称之为...
Thing is, wheather you call...
URL::route('checkSecondName', $item->PK_item_id)
或...
URL::route('checkFirstName', $item->PK_item_id)
... Laravel将生成相同的URL路径,即-/game/{itemId}
.存在命名路由是为了方便.最后,重要的是Route声明中指定的路径.
...Laravel will generate the same URL path, which is - /game/{itemId}
. Named routes exist for convenience. In the end what's important is the path specified in Route declaration.
因此,发生的是Laravel检查路径以找到匹配的路线,但是在您的情况下有两个匹配项.最后一个是根据设计选择的.
So, what happens is Laravel checks the path to find matching route, but in your case there's two matches. The last one is chosen by design.
这应该告诉您非常简单:您不能使用相同的路由来调用不同的控制器方法.可以所不同的是使用的动词: Route :: get('/game/{itemId}')
与 Route :: post('/game/{itemId}')
,但这只是一个旁注.
What this should tell you is pretty straightforward: you cannot have the same route calling different controller methods. What can be different is the verb used: Route::get('/game/{itemId}')
is not the same as Route::post('/game/{itemId}')
, but that's just a sidenote.
这里可以做的是具有额外的参数来确定要执行的操作的类型:
What could be done here is e.g. having an extra param to determine a type of action to be done:
路线
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
}
}
这篇关于如何使用laravel 4使用不同的控制器和相同的URL进行路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!