LoginSignup
0
2

More than 3 years have passed since last update.

Laravelでモーダル画面から関連した投稿の削除機能を行う

Posted at

LaravelでCRUD掲示板を作成していた際、モーダルウィンドウから投稿を削除するかユーザーに選択してもらい削除機能を実装しようとしたがかなりハマったのでメモ。

原因

HTML側から記事の投稿IDを引数に選択してなかったこと。
JS側で処理が呼び出された際にどの投稿IDかわからずずっと一意の投稿IDのみが選択されていた。

行ったこと

モーダルを投稿の数だけ配列で回して用意した
JSを呼び出す際に引数を指定してJSと紐付けた

コード

main.js

let modalMenu = false;

//HTMLからの引数から投稿IDを取得
let editModal = function(id) {

//.editModal-投稿IDと一致するものを定数に格納
 let checkForm = document.querySelector('.editModal-' + id);
 scrollTo(0,0);
 if(modalMenu === false) {
   checkForm.style.display = "flex";
   modalMenu = true;
  }
 else if(modalMenu === true) {
   checkForm.style.display = "none";
   modalMenu = false;
  }
}

index.blade.php
@foreach($posts as $post)
<div class="post-frame">
            <div class="top-picture">
                <img src="{{ asset('images/image.jpg') }}">
            </div>
            <div class="user-tweet">
                <p>{{ $post->text }}</p>
                @if (!empty($post->file))
                    <p><img src="{{$post->file}}" width="200px" height="200px"></p> 
                @endif
                <div class="user-information">
                    {{ $post->name . " " . $post->created_at}}
                </div>
                <div class="link">
                    @if ( Auth::id() === $post->user_id )
                    <!-- deleteModalの呼び出し引数に投稿IDを指定する -->
                    <label onclick="deleteModal({{$post->id}})">削除</label>
                    <label id="edit-form" onclick="editModal({{$post->id}})">編集</label>
                    @endif
                </div>
            </div>
        </div>
<!-- JSからモーダルに呼び出される側、edit-modalがmodalの本体 editModal-(投稿ID)で投稿とモーダル画面を紐付けをしている -->
    <div class="edit-modal editModal-{{ $post->id }}">
        <div class="modal-content">
            <h2>投稿編集</h2>
            <form method="POST" enctype="multipart/form-data" action="{{ url('users/posts/update/') }}/{{$post->id}}">
                @csrf
                <textarea name="text" cols="30" rows="10"></textarea>
                {{ $post->id }}
                <div class="line-right">
                    <!-- モーダルを閉じるボタン(関数名と一致させないとモーダルが閉じません) -->     
                    <button type="button" class="left-button" onclick="editModal({{ $post->id }})">キャンセル</button>
                     <!-- 送信ボタン -->
                    <button type="submit" class="right-button" onclick="editModal({{ $post->id }})">保存</button>
                </div>
            </form>
        </div>
    </div>
@endforeach

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