Laravelの基本はこちらから学べます

Laravel8で掲示板を作成する④(削除・編集機能)




こんにちは!今回はLaravel8 Livewire で掲示板を作成しようの続き。
削除・編集機能を実装して完成させましょう!

編集機能を作る

まずは、blade ファイルを作成していきましょう。
create.blade.php とさほど変更点はありませんので、復習に見ていきましょう。

resources/views/livewire/students/edit.blade.php

<div>
    <x-jet-modal wire:model="modalUpdateStatus">
        <x-slot name="slot">
            <div class="flex justify-between items-center border-b p-2 text-xl">
                <div></div>
                <h6 class="text-xl font-bold">編集する</h6>
                <button type="button" wire:click.prevent="closeUpdateModal()">✖</button>
            </div>
            <div class="p-10">
                <!-- content -->
                <form class="w-full">
                    <div class="md:flex md:items-center mb-6">
                        <div class="md:w-1/3">
                            <label class="block text-gray-500 font-bold md:text-right mb-1 md:mb-0 pr-4"
                                for="inline-first-name">
                                名前
                            </label>
                        </div>
                        <div class="md:w-2/3">
                            <input
                                class="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500"
                                id="inline-first-name" type="text" value="" name="firstname" wire:model="firstname">
                            @error('firstname')
                                <span class="block sm:inline text-red-700">{{ $message }}</span>
                            @enderror
                        </div>
                        <div>
                            
                        </div>
                    </div>
                    <div class="md:flex md:items-center mb-6">
                        <div class="md:w-1/3">
                            <label class="block text-gray-500 font-bold md:text-right mb-1 md:mb-0 pr-4"
                                for="inline-last-name">
                                苗字
                            </label>
                        </div>
                        <div class="md:w-2/3">
                            <input
                                class="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500"
                                id="inline-last-name" type="text" placeholder="" name="lastname" wire:model="lastname">
                                @error('lastname')
                                    <span class="block sm:inline text-red-700">{{ $message }}</span>
                                @enderror
                        </div>
                    </div>
                    <div class="md:flex md:items-center mb-6">
                        <div class="md:w-1/3">
                            <label class="block text-gray-500 font-bold md:text-right mb-1 md:mb-0 pr-4"
                                for="inline-email">
                                メールアドレス
                            </label>
                        </div>
                        <div class="md:w-2/3">
                            <input
                                class="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500"
                                id="inline-email" type="text" placeholder="" name="email" wire:model="email">
                                @error('email')
                                    <span class="block sm:inline text-red-700">{{ $message }}</span>
                                @enderror
                        </div>
                    </div>
                    <div class="md:flex md:items-center mb-6">
                        <div class="md:w-1/3">
                            <label class="block text-gray-500 font-bold md:text-right mb-1 md:mb-0 pr-4"
                                for="inline-phone-number">
                                電話番号
                            </label>
                        </div>
                        <div class="md:w-2/3">
                            <input
                                class="bg-gray-200 appearance-none border-2 border-gray-200 rounded w-full py-2 px-4 text-gray-700 leading-tight focus:outline-none focus:bg-white focus:border-purple-500"
                                id="inline-phone-number" type="text" placeholder="" name="phone" wire:model="phone">
                                @error('phone')
                                    <span class="block sm:inline text-red-700">{{ $message }}</span>
                                @enderror
                        </div>
                    </div>
                    <div class="flex justify-end">
                        <button
                            class="shadow bg-purple-500 hover:bg-purple-400 focus:shadow-outline focus:outline-none text-white font-bold py-2 px-4 rounded"
                            type="button" wire:click.prevent="update()">
                            変更する
                        </button>
                    </div>
                </form>
            </div>
        </x-slot>
    </x-jet-modal>
</div>

それではこのコードで重要な箇所を確認していきましょう。

Laravel jetstream が用意をした component を使用するためのタグ

これは前回 https://aburasoba.org/laravel8-livewire-create/ にも出てきましたね。

<x-jet-modal>
こちらを記入することで、views/vendor/jetstream/components/modal.blade.php を利用することができます。


<x-jet-slot name=”slot”>
views/vendor/jetstream/components/modal.blade.php を確認しましょう。

<x-jet-slot name=”slot”> タグに囲われた部分が、modal 内の {{ $slot }} に代入され表示されて非常に便利でしたね!
少し忘れてしまったよという方は、 https://aburasoba.org/laravel8-livewire-create/ から復習をしてみましょう。

Livewire component に定義された、メソッド、プロパティ

定義した、メソッドを発火させていますね。

wire:click.prevent=”closeUpdateModal()”
wire:click.prevent=”update()”

以下はプロパティですね。

wire:model=”firstname”
wire:model=”lastname”
wire:model=”email”
wire:model=”phone”
wire:model=”modalUpdateStatus”


次に、index.blade.php を編集していきます。

index.blade.php

// 省略


        <div class="px-6 py-4">
            <div class="font-bold text-xl mb-2">All Student</div>
            @include('livewire.students.create')
            @include('livewire.students.edit') //追加1
        </div>
        
// 省略
        @foreach ($students as $student)
          <tr>
            <td class="border px-4 py-2">{{ $student->firstname }}</td>
             <td class="border px-4 py-2">{{ $student->lastname }}</td>
             <td class="border px-4 py-2">{{ $student->email }}</td>
             <td class="border px-4 py-2">{{ $student->phone }}</td>
             <td class="border px-4 py-2">  //以下追加2
               <button type="button" class="bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border border-gray-400 rounded shadow" wire:click.prevent="openUpdateModal({{ $student->id }})">編集</button>
             </td> 
             <td class="border px-4 py-2">削除</td>
           </tr>
         @endforeach

edit.blade.php を include し、編集ボタンを追加しました。

下記のように、
wire:click.prevent=”openUpdateModal({{ $student->id }})”
メソッドには引数を渡すことが可能です。今回は、生徒のIDを引数として渡しています。

Livewire component にメソッド・プロパティを追記していく

それでは編集、更新用で追加したメソッド・プロパティをコンポーネントに追加していきましょう。

app/Http/Livewire/Students.php

//以下、追加部分のみ記載

public $modalUpdateStatus;

public function openUpdateModal($id) //
    {
        $student = Student::where('id', $id)->first();
        $this->ids = $student->id;
        $this->firstname = $student->firstname;
        $this->lastname = $student->lastname;
        $this->email = $student->email;
        $this->phone = $student->phone;
        $this->modalUpdateStatus = true;
    }

 public function closeUpdateModal()
    {
        $this->modalUpdateStatus = false;
    }


public function update()
    {
        $validatedData = $this->validate([
            'firstname' => 'required',
            'lastname' => 'required',
            'email' => 'required|email',
            'phone' => 'required',
        ]);
        if ($this->ids) {
            $student = Student::find($this->ids);
            $student->update([
                'firstname' => $this->firstname,
                'lastname' => $this->lastname,
                'email' => $this->email,
                'phone' => $this->phone,
            ]);
            session()->flash('message', '投稿の編集に成功しました。');
            $this->resetInputFields();
            $this->closeUpdateModal();
        }
    }

まずは $modalUpdateStatus こちらはedit.blade.php に記載のmodalの表示をになっています。

openUpdateModal($id
$id は index.blade.php に記載の wire:click.prevent=”openUpdateModal({{ $student->id }})”
の引数です。
このメソッドでは、受け取った$idで該当の生徒の情報をモデルを利用し取得。初期値としてデータを保持しています。

closeUpdateModal() こちらは updateModal を閉じるメソッドですね。

update()
入力内容をバリデート。バリデーションを通れば、更新処理をしています。

ここまでくれば、更新処理の完成です!
実際にアプリケーションを操作してみましょう!

削除機能をつける

CRUD機能のラスト、削除機能をつけていきましょう!

まずは生徒一覧に削除ボタンを設置していきます。

index.blade.php

// 省略

<td class="border px-4 py-2">
    <button type="button" class="bg-white hover:bg-gray-100 text-gray-800
     font-semibold py-2 px-4 border border-gray-400 rounded shadow"    
     wire:click.prevent="openUpdateModal({{ $student->id }})">
     編集</button>
</td> 
// 以下追加
<td class="border px-4 py-2">
    <button type="button" class="bg-white hover:bg-gray-100 text-gray-800 
    font-semibold py-2 px-4 border border-gray-400 rounded shadow"
    wire:click.prevent="delete({{ $student->id }})">
   削除</button>
</td>

delete({{ $student->id }})
delete メソッドに生徒のIDを引数として渡しています。

それではdelete メソッドを定義していきましょう!

app/Http/Livewire/Students.php

//以下、追加部分のみ記載

public function delete($id)
    {
        if($id)
        {
            Student::where('id', $id)->delete();
            session()->flash('message', '投稿の削除に成功しました。');
        }
    }

以上です!モデルを通して、$idで該当の生徒を取得、削除しています。

お疲れ様でした!全4回に渡って、認証からCRUD機能を作成していきましたがいかがでしたでしょうか?

今までLaravelだけではできなかった非同期の掲示板を簡単に作成できましたね!
ぜひこの掲示板から拡張を行ってみてください!

私も拡張していきます!




コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です