0
1

More than 3 years have passed since last update.

PHP Laravel 6 おすすめ映画投稿サイト作成過程 5:更新機能作成編

Last updated at Posted at 2020-09-23

ルーティング

更新ページにはeditを使用します。

| GET|HEAD  | recommends/{recommend}/edit | recommends.edit    | App\Http\Controllers\RecommendController@edit                          | web          |

更新をDBに登録するにはupdateを使用します。

| PUT|PATCH | recommends/{recommend}      | recommends.update  | App\Http\Controllers\RecommendController@update                        | web          |

viewの作成

Screen Shot 2020-09-23 at 22.54.37.png

editに対するコントローラーの作成

recommend/app/Http/Controllers/RecommendController.php
public function edit(Recommend $recommend)
    {
      return view('recommends.edit');
    }

editへのリンクをindexに追加

recommend/resources/views/recommends/index.blade.php
<table>
  <thead>
    <tr>
      <th>タイトル</th>
      <th>画像:現在は空</th>
      <th>URL</th>
      <th>操作</th>
    </tr>
  </thead>
  @foreach($recommends as $recommend)
    <tr>
      <td>{{$recommend->title}}</td>
      <td>{{$recommend->image_file_name}}</td>
      <td>{{$recommend->url}}</td>
      <td><a href="{{route('recommends.show', $recommend->id)}}">詳細</a></td>
      <td><a href="{{route('recommends.edit', ['recommend' => $recommend])}}">編集</a></td>
    </tr>
  @endforeach
</table>

editからコントローラーへ更新内容を飛ばす

formタグで更新した内容を飛ばします。
この時、@method('PUT')を忘れずに。

recommend/resources/views/recommends/edit.blade.php
<table>
  <thead>
    <tr>
      <th>タイトル</th>
      <th>映画URL</th>
      <th>概要</th>
      <th>感想</th>
    </tr>
    <tr>
      <th><input type="text" name='title'></th>
      <th><input type="URL" name='url'></th>
      <th><textarea name="description" id="" cols="30" rows="10"></textarea></th>
      <th><textarea name="Impressions" id="" cols="30" rows="10"></textarea></th>
      </tr>
   </thead>

DBの更新

editから受け取った内容を、Modelのアップデートメソッドを使用して更新します。

recommend/app/Http/Controllers/RecommendController.php
 public function update(Request $request, Recommend $recommend)
    {
        $recommend->update($request->all());
        return redirect()->route('recommends.show', compact('recommend'));
    }
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1