データ更新ページupdateと削除ページdestroy
コントローラーにEditメソッド追加
app/Http/Controllers/TestController.php
1 2 3 4 5 6 |
public function edit($id) { $data = []; $data['categories'] = self::CATEGORY_LIST; $data['test'] = Test::find($id); return view('test/edit', $data); } |
GETで受け取った$idでデータを検索してビューに渡すだけね。
ビュー:test/edit.blade.phpを作成
resources/views/test/edit.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
@extends('layouts.app') @section('content') <div class="container"> <div class="panel panel-default"> <h2 class="text-white bg-secondary">変更</h2> <a href="/test"><button class="btn btn-primary">一覧に戻る</button></a> <form action="/test/{{ $test->id }}" method="POST"> @csrf @method('PUT') <div class="form-group"> <label>タイトル</label> <input type="text" name="title" value="{{ old('title', $test->title) }}" class="form-control"> @if($errors->has('title')) <span class="text-danger">{{ $errors->first('title') }}</span> @endif </div> <div class="form-group"> <label>カテゴリ</label> <select name="category" class="form-control"> <option value="">選択してください</option> @foreach ($categories as $key => $category) <option value="{{ $key }}"@if($key == old('category', $test->category)) selected @endif>{{ $category }}</option> @endforeach </select> @if($errors->has('category')) <span class="text-danger">{{ $errors->first('category') }}</span> @endif </div> <div class="form-group"> <label>説明</label> <textarea name="description" class="form-control">{{ old('description', $test->description) }}</textarea> @if($errors->has('description')) <span class="text-danger">{{ $errors->first('description') }}</span> @endif </div> <button type="submit" class="btn btn-primary">変更</button> </form> </div> </div> @endsection |
※DELETE同様 @method(‘PUT’) で
を生成してくれるよ。
※ヘルパー関数 old($value, $default]) は第1引数が存在しなければ第2引数をデフォルトとして出力するよ!
コントローラーにUpdateメソッド追加
app/Http/Controllers/TestController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public function update(Request $request, $id) { // バリデーション $this->validate($request, [ 'title' => 'required', 'category' => 'required', 'description' => 'required', ], [ 'title.required' => 'タイトルを入力してください', 'category.required' => 'カテゴリを選択してください', 'description.required' => '説明を入力してください', ] ); // $test = Test::find($id); $test->fill($request->all())->save(); return redirect('test'); } |
①find()でModelオブジェクトを取得。
②fill()でModelオブジェクトのプロパティを更新。
③save()で保存。
コントローラーにdestroyメソッドを追加
app/Http/Controllers/TestController.php
1 2 3 4 5 |
public function destroy($id) { Test::find($id)->delete(); return redirect('test'); } |
①find()でModelオブジェクトを取得。
②delete()でModel削除