多应用+插件架构,代码干净,支持一键云编译,码云点赞13K star,4.8-4.12 预售价格198元 广告
现在介绍 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> ~~~ 恭喜,现在你可以新建、显示、列出、更新、删除文章了。