我們已經說明了 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) }}
~~~