Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JackD's avatar
Level 6

Delete item in foreach data

Hi,

i have this foreach code for the list of my data

<ul>
@foreach($posts as $data)

    <li>{{ $data->name }}
    
    <form method="post" action="{{url('delete/post/'.$data->id)}}" class="delete_post" id="deleteForm">
            {{ csrf_field() }}
        </form>

        <button class="btn btn-danger" id="delete">Delete</button>  

    </li>


@endforeach
</ul>

and this javascript to trigger the delete confirmation of sweetalert

    $('button#delete').on('click', function () {
        swal({
                    title: "Are you sure?",
                    text: "You will not be able to recover this after delete.",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "Yes, delete it!",
                    cancelButtonText: "No, cancel please!",
                    closeOnConfirm: false,
                    closeOnCancel: false
                },

                function (isConfirm) {
                    if (isConfirm) {
                        $("#deleteForm").submit();
                        swal("Deleted!", "Successfully", "success");
                    }

                    else {
                        swal("Cancelled", "Cancelled.", "error");
                    }
                });
    })

my question is how can delete the specific post? because when i test it, it deletes the first item not the item where i click the delete button

Thanks

0 likes
3 replies

Please or to participate in this conversation.