現在介紹 CRUD 中的 D,從數據庫中刪除文章。按照 REST 架構的約定,刪除文章的路由是:
> DELETE articles/{articles} | articles.destroy | ArticlesController@destroy
刪除資源時使用 DELETE 請求。如果還使用 GET 請求,可以構建如下所示的惡意地址:
~~~
<a href='http://example.com/articles/1/destroy'>look at this cat!</a>
~~~
刪除資源使用 DELETE 方法,路由會把請求發往 app/controllers/ArticlesController.php 中的 destroy 動作。修改 destroy 動作:
~~~
public function destroy($id)
{
Article::destroy($id);
return Redirect::route('articles.index');
}
~~~
想把記錄從數據庫刪除,可以在模型對象上調用 destroy 方法。注意,我們無需為這個動作編寫視圖,因為它會轉向 index 動作。
最后,在 index 動作的模板(app/views/articles/index.blade.php)中加上“Destroy”鏈接:
~~~
<table>
<tr>
<th>Title</th>
<th>Text</th>
<th colspan="2"></th>
</tr>
@foreach ($articles as $article)
<tr>
<td>{{ $article->title }}</td>
<td>{{ $article->text }}</td>
<td>{{ link_to_route('articles.show', 'Show', $article->id) }}</td>
<td>{{ link_to_route('articles.edit', 'Edit', $article->id) }}</td>
<td>
{{ Form::open(array('method' => 'DELETE', 'route' => array('articles.destroy', $article->id))) }}
{{ Form::submit('Delete') }}
{{ Form::close() }}
</td>
</tr>
@endforeach
</table>
~~~
恭喜,現在你可以新建、顯示、列出、更新、刪除文章了。