2016-11-11 75 views
0

我已經使用Laravel創建了一個基本博客,然後當我嘗試將刪除方法添加到「顯示」視圖中,但在確認刪除後,沒有任何反應進一步。Laravel5 link_to_action在嘗試刪除文章時不起作用

的路線是這樣的:

DELETE  | articles/{articles} | articles.destroy | App\Http\Controllers\[email protected] 

我的代碼看起來如下:

在所謂的「秀」的視圖,其中顯示所選的文章,下面我想添加喜歡的鏈接:

{!! link_to_action('[email protected]', 'Delete Article', $article->id, ['method'=>'DELETE', 'class'=>'btn btn-danger', 'onClick'=>'return confirm("Are you sure you want to delete this item?")']); !!} 

在ArticlesController,我寫了 '破壞' 功能,正如:

public function destroy(Article $article) { 

     $article->delete(); 

     return redirect('articles')->with([ 
      'flash_message' => 'Article successfully deleted.', 
      'flash_message_important' => 'true', 
     ]); 
    } 
+1

不應該'刪除|文章/ {文章}'是'DELETE |文章/ {文章}'? – Matey

+0

@Matey AFAIK'文章/ {文章}'在Laravel 5.3中變成'articles/{article}'。 [https://laravel.com/docs/5.3/upgrade](https://laravel.com/docs/5.3/upgrade)在Routing下: 在Laravel 5.3中,默認情況下所有的資源路由參數都是單一化的。因此,與Route :: resource相同的調用將註冊以下URI: '/ photos/{photo}' –

回答

3

問題出在link_to_action,Laravel 5中沒有包含此問題。請參閱this post

要使用link_to_route幫助程序,您需要拉動"laravelcollective/html": "~5.0"程序包。

+0

其實我從Laravel 5 Fundamentals培訓中學到了這個方法,所以我不會期望這個發生。我用'DELETE'方法替換了'form'元素的鏈接,所以現在一切正常。謝謝你的幫助! – sklrboy

+0

@sklrboy我建議你發佈這個作爲你的問題的答案,以防有人在未來遇到同樣的問題。 – Wistar

+1

我投票答覆,因爲它解決OP問題,並通知其他人。我相信這應該被標記爲接受... –

0

您正在通過$article->id刪除請求參數。而您正試圖在destroy()方法中檢索Article對象。那是錯的。

修改您的破壞方法如下

public function destroy($article_id) 
    { 
    Article $article = Article::find($article_id); 
    if ($article != null) { 
     $article->delete(); 
     return redirect('articles')->with([ 
      'flash_message' => 'Article successfully deleted.', 
      'flash_message_important' => 'true', 
     ]); 
    } 
} 

,它會工作。

+1

出於好奇,你爲什麼要檢查文章是否爲空?如果文章沒有找到,那麼'findOrFail'會拋出異常。 –

+0

你最近一直在寫Java嗎?我不認爲PHP會喜歡'Article $ article = Article :: findorFail($ article_id);'。 Laravel也做了隱式路由綁定,所以如果一個ID被傳遞了,Laravel實際上會傳入一個Article Article的實例到這個函數中,即使它看起來會接收一個ID。 https://laravel.com/docs/5.3/routing#route-model-binding – user3158900

+0

@ChrisForrence:你說得對。修改我的答案。 @ user3158900:是的,在android應用上工作。但拉拉維爾確實有'findorFail'。請參閱:https://laravel.com/docs/5.3/eloquent#retrieving-single-models –