15.
刪除題目
-
當 route 刪除使用 delete方法時,無法直接用連結的方式來做,因為連結的方法屬於get。所以我們自行產生表單,並送出_method值為DELETE的參數,可以利用 Laravel 5.6 新的@method('delete')來達成,以及用@csrf(取代原先的csrf_field())產生令牌,以加入CSRF保護,避免跨站攻擊。詳情:https://d.laravel-china.org/docs/5.6/csrf
-
修改 /專案/resources/views/show.blade.php 樣板,加入刪除按鈕:
@can('建立測驗')
<form action="{{route('topic.destroy', $topic->id)}}" method="post" style="display:inline">
@csrf
@method('delete')
<button type="submit" class="btn btn-danger">刪除</button>
</form>
<a href="{{route('topic.edit', $topic->id)}}" class="btn btn-warning">編輯</a>
({{$topic->ans}})
@endcan
- 其中
style="display:inline"只是為了讓刪除按鈕可以和其他按鈕放在一起。
- 此外,要注意的是,form中的
method="post"也不可拿掉
-
編輯路由 /專案/routes/web.php 加入 topic 的刪除路由
Route::delete('/topic/{topic}', 'TopicController@destroy')->name('topic.destroy');

- 接著在控制器中
/專案/app/Http/Controllers/TopicController.php,加入 delete 的方法:
public function destroy(Topic $topic)
{
$topic->delete();
return redirect()->route('exam.show', $topic->exam_id);
}
- 當我們沒有使用路由模型綁定時,也可以用靜態方法的
destroy()也可以,但此例我們需要抓出exam_id的值,故用destroy()也沒比較省事,因此底下參考一下即可。
public function destroy($id)
{
Topic::destroy($id);
return redirect()->route('exam.show', $id);
}
destroy()用法(詳細請參考:)https://laravel-china.org/docs/laravel/5.6/eloquent/1403#bb7a2e:
//刪除一筆
Topic::destroy(1);
//刪除多筆
Topic::destroy([1,3,5,7]);
Topic::destroy(1,3,5,7);