LoginSignup
3
2

Laravelで削除確認メッセージを出す方法

Posted at

概要

この確認は正直どこでも使うので
汎用性が高いと考え記事にしました。

バージョン

  • laravel 9.x
  • composer 2.5.8
  • php 8.1

対象コード

<form id="delete_{{ $contact->id }}" class="mt-40" method="post" action="{{ route('contacts.destroy', ['id' => $contact->id ])}}">
        @csrf
        <div class="p-2 w-full">
          <a href="#" data-id="{{ $contact->id }}" onclick="deletePost(this)" class="flex mx-auto text-white bg-pink-500 border-0 py-2 px-8 focus:outline-none hover:bg-pink-600 rounded text-lg">削除する</a>
        </div>
        </form>
        
<script>
        function deletePost(e){
            'use strict'
            if(confirm('本当に削除しますか?')){
                document.getElementById('delete_' + e.dataset.id).submit()
            }
        }

    </script>

onclick

<a href="#" data-id="{{ $contact->id }}" onclick="deletePost(this)" class="flex mx-auto text-white bg-pink-500 border-0 py-2 px-8 focus:outline-none hover:bg-pink-600 rounded text-lg">削除する</a>

onclickはクリックしたらどのような処理を行うか設定することができます。
今回は"deletePost(this)"という名前を設定して、javascriptでdeletePost(e)と指定しています。

this は function を呼んだ時の . の前についているオブジェクトを指します。ここで言うと
e.dataset.idのeを指します。

thisが分からない人は以下の記事がすごくわかりやすいので、見てください。

<script>
        function deletePost(e){
            'use strict'
            if(confirm('本当に削除しますか?')){
                document.getElementById('delete_' + e.dataset.id).submit()
            }
        }

    </script>

getElementByIdはwebからマッチしたidの中身を取得する関数です。

e.dataset.idは分けるとこんな感じかな?
e=「クリックしたら」 dataset=「htmlのdata-id」 の id=「form id="delete_{{ $contact->id }}"」を登録する
こんなイメージ。
分からなければ私の語彙力不足です。
申し訳ありません。

document.getElementById('delete_' + e.dataset.id).submit()

結論

thisの解説がかなり良質なので、様々なサイトを見た後にこれを、見に来るとわかりやすいかもしれないです。

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