2015-10-28 57 views
1
Route::get('post/form/{id}', array('as' => 'admin.post.delete', 'uses' => "[email protected]")); 

Route::get('post/form', array('as' => 'admin.post.create', 'uses' => "[email protected]")); 

我想結合兩個路由上面的兩個函數,創建和刪除路由。因爲這兩條路線只有不同的id在Laravel 5.1中可以使用兩種功能的路線嗎?

Route::get('post/form/{id}', array('as' => 'admin.post', 'uses' => "[email protected]")); 

如果我想輸入沒有id,它會重定向到創建函數。如果我輸入id,它將重定向到刪除功能。

我怎樣才能使用一個路線的兩個功能?

+0

你想要做的事情是非常不切實際的,你能不能更新刪除路由到'post/form/{id}/delete'並且有'post/form/{id}'作爲show route? – James

回答

1

2種方法不能使用1種路線。 解決方法是使用1種方法,例如激發具體方法。

routes.php文件

get('post/form/{id?}', '[email protected]'); 

PostController.php

public function form($id = null) { 
    return $id ? $this->deleteForm($id) : $this->createForm(); 
} 

但是使用2路要簡單得多。

+0

這是我想要的。它工作得很好!感謝您的幫助 –

1

正如詹姆斯所說,這不是很實際,但你可以通過以下方式實現。

Laravel爲您提供了定義可選路由參數的可能性,如下所示。

Route::get('user/{name?}', function ($name = null) { 
    return $name; 
}); 

Route::get('user/{name?}', function ($name = 'John') { 
    return $name; 
}); 

Laravel文檔關於路由參數:Laravel Route Parameters

因此,這意味着你可以只讓你這樣的路線。

Route::get('post/form/{id?}', array('as' => 'admin.post', 'uses' => "[email protected]")) 

在你的控制器中,你需要檢查'id'是否存在。如果沒有,則創建用戶。如果'id'存在,則刪除該用戶。