[英]Call controller with href on Laravel
我正在嘗試使用href調用控制器,但出現錯誤,我需要傳遞一個參數。 我這樣做
<a href="{{ link_to_action('StoriesController@destroy', $story->id) }}" class="delete"><i class="material-icons" title="Delete"></i></a>
控制器代碼
public function destroy(Story $story)
{
$story = Story::find($id);
$story->delete();
return redirect('/stories')->with('success', 'Historic Removed');
}
錯誤缺少路線的必需參數:stories.destroy-> 錯誤
link_to_action()
幫助器會生成一個實際的HTML鏈接,它是一個<a>
標記。 因此,您已經錯誤地使用了它。
但是,您遇到的錯誤很可能與此無關。
鏈接到路線的最佳方法是使用route()
幫助器:
<a href="{{ route('index.index', $yourParam) }}">link</a>
以及路線定義:
Route::get('/someroute/{:param}', ['uses' => 'IndexController@index', 'as' => 'index.index']);
注意as
鍵,它將為此路由分配一個名稱。 你也可以打電話
Route::get(...)->name('index.index')
產生相同的結果。
我可能是錯的,但是在html中,您正在傳遞一個整數,盡管在控制器中,函數期望使用Story對象。 只需將Story story
更改為$id
,它應該很好。
無論如何,沒有實際錯誤不能說更多。
您應該以這種方式使用它:由於根據laravel函數link_to_action的說明,第一個參數將是控制器功能路徑,第二個將是名稱,第三個將是必需參數的數組:
<a href="{{ link_to_action('StoriesController@destroy', 'destory',[$story->id]) }}" class="delete"><i class="material-icons" title="Delete"></i></a>
您也可以從這里獲得幫助
由於您接受$story
作為模型對象,因此不必使用Story::find()
,也不必在您的destroy方法中定義$id
,將代碼更改為:
public function destroy(Story $story)
{
$story->delete();
return redirect('/stories')->with('success', 'Historic Removed');
}
希望能幫助到你。
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.