LoginSignup
0
0

More than 3 years have passed since last update.

一覧表示・新規登録・編集・削除まとめ(Laravel7.x系)

Last updated at Posted at 2020-07-27

はじめに

いつもググっては結果を書き留めておく習慣がなかったためqiitaに備忘録として残します。
今回はLaravel7.x系で新規登録、編集、削除の実装を行います。
※今回の例だと別に6系でも5系でも書き方変わリません。

前提

環境

  • Mac OS
  • Composer version 1.10.9
  • Laravel Framework 7.21.0
  • PhpStorm、MAMP(MySQL)使用

実装一覧

誰がどの部署に所属しているのかを一覧にしています。特になんの変哲もないテーブルです。
そのうち拡張してリレーション組みたいですね。

id 名前 年齢 所属部署
1 A子 33 営業部
2 B夫 44 総務部
3 C美 27 技術部
4 B夫 51 経理部

ディレクトリ一覧

app
├── Http
│   ├── Controllers
│   │   └── MeibosController.php
└── Models
  └── Meibos.php

resources
└── views
└── meibos
   ├── index.blade.php
   ├── register.blade.php
   ├── remove.blade.php
   └── update.blade.php

ルーティング一覧

URI HTTPメソッド アクション名 名前
/test/list GET MeibosController@index test.index
/test/register/new GET MeibosController@new test.new
/test/register/create POST MeibosController@create test.create
/test/edit/{id} GET MeibosController@edit test.edit
/test/update/{id} POST MeibosController@update test.update
/test/remove/{id} POST MeibosController@remove test.destroy

実装

ここから実装に移ります。順番としては新規登録、編集、削除の順。

一覧表示

Model(Meibos)

meibosテーブルの設定を表示しています。更新時に一括で更新を行いたいためfillableで更新項目を設定しています。今回は'name','age','departments'の3項目です。

app/Models/Meibos.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Meibos extends Model
{
    protected $table = 'meibos';
    protected $primaryKey = 'id';
    protected $fillable = [
        'name','age','departments','updated_at'
    ];
}

Controller(MeibosController)

モデルから全データを引っ張ってくるだけです。値をviewへ渡すためにcomapctを使います。

app/Http/Controllers/MeibosController.php
    //リスト一覧
    public function index(){
        $meibos = Meibos::all();
        return view('meibos.index',compact('meibos'));
    }

index(View)

次はリスト一覧を表示するためのviewです。テスト用なので簡易的です。
@csrfは予期しないリクエスト等、webアプリケーションの脆弱性から保護してくれる便利機能…と私は解釈しています。
参考: https://readouble.com/laravel/7.x/ja/csrf.html

formタグのうちどこでもいいので入れておきましょう。

resources/views/meibos/index.blade.php
@foreach($meibos as $meibo)
<tr>
 <td class="id"><a href="{{ route('test.edit',$meibo->id) }}">{{ $meibo- 
 >id }}</a></td>
 <td class="other">{{ $meibo->name }}</td>
 <td class="other">{{ $meibo->departments }}</td>
 <td class="other">{{ $meibo->age }}</td>
 <td class="btn">
 <form action="{{ route('test.destroy',$meibo->id) }}" method="POST">
 @csrf
 <input type="submit" value="削除" class="delete_btn2">
 </form>
 </td>
</tr>
@endforeach

新規登録

インスタンスを作ってその中にinputデータを保存する形となります。
リクエストは別途FormRequestで作った方が見栄えはいいんですけどそれは後日拡張しましょう。

Controller(MeibosController)

app/Http/Controllers/MeibosController.php
    //登録(view)
    public function new(){
        return view('meibos.register');
    }

    //登録(実装)
    public function create(Request $request){
        $request->validate([
            'name' => 'required | string | max:255',
            'departments' => 'required | string | max:255',
            'age' => 'required | integer'
        ]);

        $meibos = new Meibos;
        $meibos->fill($request->all())->save();

        return redirect('/test/list');
    }

register(View)

新規登録画面用のviewです。こちらも記事用のテストデータなので簡易的な作りとしています。

resources/views/meibos/register.blade.php

<ul>
 @foreach($errors->all() as $error)
  <li class="error">{{ $error }}</li>
 @endforeach
</ul>
 <form action="{{ route('test.create') }}" method="POST">
  @csrf
  <label for="name">名前</label>
  <input type="text" name="name" required>

  <label for="age">年齢</label>
  <input type="number" name="age" required>

  <label for="departments">所属部署</label>
  <input type="text" name="departments" required>

  <input type="submit" class="submit_btn" value="登録">
</form>

編集

find()でDBからデータを取得する。個別ページにする必要があるのでidを指定。$idには主キーが入る仕組み。

Controller(MeibosController)

app/Http/Controllers/MeibosController.php
    //修正
    public function edit($id){
        $meibo = Meibos::find($id);
        return view('meibos.update',compact('meibo'));
    }

    public function update(Request $request,$id){
        $meibo = Meibos::find($id);

        $request->validate([
            'name' => 'required | string | max:255',
            'departments' => 'required | string | max:255',
            'age' => 'required | integer'
        ]);

        $meibo->fill($request->all())->save();

        return redirect('/test/list');
    }

update(View)

edit()メソッドでcompactを紐づけたため$meiboを使ってDBデータを引っ張ってこれます。

resources/views/meibos/update.blade.php
<ul>
 @foreach($errors->all() as $error)
 <li class="error">{{ $error }}</li>
 @endforeach
</ul>

<form action="{{ route('test.update',$meibo->id) }}" method="POST">
 @csrf
 <label for="name">名前</label>
 <input type="text" name="name" required value="{{ $meibo->name }}">

 <label for="age">年齢</label>
 <input type="number" name="age" required value="{{ $meibo->age }}">

 <label for="departments">所属部署</label>
 <input type="text" name="departments" required value="{{ $meibo->departments }}">

 <input type="submit" class="submit_btn" value="修正">
</form>

削除

全部消したければ別ですが編集する時と同じように個別で指定する必要があるため$id必須。

Controller(MeibosController)

app/Http/Controllers/MeibosController.php

    public function destroy($id){
        Meibos::find($id)->delete();
        return redirect('/test/list');
    }

登録情報のような重要なデータだったら確認ページを挟んだ方が閲覧者の誤作動を防げますが、今回はただLaravelの挙動確認するための記事なので割愛します。

index(View)

編集時と同様viewでは遷移先にidのデータを渡す必要があります。そのための$meibo->idです。

resources/views/meibos/index.blade.php
<td class="btn">
 <form action="{{ route('test.destroy',$meibo->id) }}" method="POST">
 @csrf
 <input type="submit" value="削除" class="delete_btn2">
 </form>
</td>

終わりに

以上で一覧表示、新規登録、編集、削除のまとめを終了します。
認証絡んでなければ今回みたいに気楽にデータ引っ張ってきて面白いんですけどね。
こんな感じでしばらくの間備忘録用にLaravel関係の記事をアップします。

お読みいただきましてありがとうございます。
お役に立てれば幸いです。そうでなければ申し訳ございません。
ではまたの機会に。

参考URL

0
0
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
0