こちらのページの続きです。
Laravel で MariaDB の CRUD (その 4)
データ更新機能を作ります。
- ルーティングを確認
- 一覧ページに編集のリンクをつけます。
- 詳細のページに編集のリンクをつけます。
- editアクションを編集
- ビューの作成
- updateアクションを編集
- サーバーを起動してブラウザーで確認
articles.update があることを確認
php artisan route:list
resources/views/articles/index.blade.php
{{-- layoutsフォルダのapplication.blade.phpを継承 --}}
@extends('layouts.application')
{{-- @yield('title')にテンプレートごとにtitleタグの値を代入 --}}
@section('title', '記事一覧')
{{-- application.blade.phpの@yield('content')に以下のレイアウトを代入 --}}
@section('content')
<div>
<a href="/articles/create">新規作成</a>
</div>
<table>
@foreach ($articles as $article)
<tr>
<td>{{$article->title}}</td>
<td>{{$article->body}}</td>
<td><a href="/articles/{{$article->id}}">詳細を表示</a></td>
<td><a href="/articles/{{$article->id}}/edit">編集する</a></td>
</tr>
@endforeach
</table>
@endsection
resources/views/articles/show.blade.php
{{-- layoutsフォルダのapplication.blade.phpを継承 --}}
@extends('layouts.application')
{{-- @yield('title')にテンプレートごとの値を代入 --}}
@section('title', '記事詳細')
{{-- application.blade.phpの@yield('content')に以下のレイアウトを代入 --}}
@section('content')
<h1>{{$article->title}}</h1>
<p>{{$article->body}}</p>
<br><br>
<a href="/articles/{{$article->id}}/edit">編集する</a>
<a href="/articles">一覧に戻る</a>
@endsection
app/Http/Controllers/ArticlesController.php
// 略
public function edit($id)
{
$article = Article::find($id);
return view('articles.edit', ['article' => $article]);
}
// 略
resources/views/articles/edit.blade.php
{{-- layoutsフォルダのapplication.blade.phpを継承 --}}
@extends('layouts.application')
{{-- @yield('title')にテンプレートごとの値を代入 --}}
@section('title', '編集')
{{-- application.blade.phpの@yield('content')に以下のレイアウトを代入 --}}
@section('content')
<form action="/articles/{{$article->id}}" method="post">
{{ csrf_field() }}
<div>
<label for="title">タイトル</label>
<input type="text" name="title" placeholder="記事のタイトルを入れる" value="{{$article->title}}">
</div>
<div>
<label for="body">内容</label>
<textarea name="body" rows="8" cols="80" placeholder="記事の内容を入れる">{{$article->body}}</textarea>
</div>
<div>
<input type="hidden" name="_method" value="patch">
<input type="submit" value="更新">
</div>
</form>
@endsection
app/Http/Controllers/ArticlesController.php
// 略
public function update(Request $request, $id)
{
// idを元にレコードを検索して$articleに代入
$article = Article::find($id);
// editで編集されたデータを$articleにそれぞれ代入する
$article->title = $request->title;
$article->body = $request->body;
// 保存
$article->save();
// 詳細ページへリダイレクト
return redirect("/articles/".$id);
}
// 略
php artisan serve
http://localhost:8000/articles
編集するをクリック
更新をクリック
一覧に戻るをクリック