5.11 更新文章
我们已经说明了 CRUD 中的 CR 两种操作。下面进入 U 部分,更新文章。
首先,要在 ArticlesController 中更改 edit 动作:
public function edit($id)
{
$article = Article::find($id);
return View::make("articles.edit", compact("article"));
}
视图中要添加一个类似新建文章的表单。新建 app/views/articles/edit.blade.php 文件,写入下面的代码:
<h1>Editing Article</h1>
@if ($errors->any())
<div id="error_explanation">
<h2>{{ count($errors->all()) }} prohibited
this article from being saved:</h2>
<ul>
@foreach ($errors->all() as $message)
<li>{{ $message }}</li>
@endforeach
</ul>
</div>
@endif
{{ Form::open(array("route" => array("articles.update", $article->id), "method" => "put")) }}
<p>
{{ Form::text("title", $article->title) }}
</p>
<p>
{{ Form::text("text", $article->text) }}
</p>
<p>
{{ Form::submit("submit") }}
</p>
{{ Form::close() }}
{{ link_to_route("articles.index", "Back") }}
这里的表单指向 update 动作
method: put ( patch ) 选项告诉 Laravel,提交这个表单时使用 PUT 方法发送请求。根据 REST 架构,更新资源时要使用 HTTP PUT 方法。
然后,要在 app/controllers/ArticlesController.php 中更新 update 动作:
public function update($id)
{
$rules = array("title" => "required|min:5");
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::route("articles.edit")
->withErrors($validator)
->withInput();
}
$article = Article::find($id);
$article->title = Input::get("title");
$article->text = Input::get("text");
$article->save();
return Redirect::route("articles.show", array($article->id));
}
最后,我们想在文章列表页面,在每篇文章后面都加上一个链接,指向 edit 动作。打开 app/views/articles/index.blade.php 文件,在“Show”链接后面添加“Edit”链接:
<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>
</tr>
@endforeach
</table>
我们还要在 app/views/articles/show.blade.php 模板的底部加上“Edit”链接:
{{ link_to_route("articles.index", "Back") }} |
{{ link_to_route("articles.edit", "Edit", $article->id) }}