You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9资源控制器destroy函数异常:删除错误用户问题

问题修复:Laravel批量删除表单提交错误

问题根源

核心问题是所有删除表单都使用了相同的id="EditForm"——HTML中id属性必须唯一,当调用document.getElementById("EditForm")时,只会匹配页面中第一个带有该id的表单,导致每次提交的都是第一个用户的删除请求,最终出现"按顺序删用户"的异常。


修复方案(推荐简洁版)

通过修改点击事件,直接传递当前按钮所在的表单,无需依赖id:

  1. 更新视图中的按钮代码
    将按钮的onclick事件改为传递当前表单:
<button type="submit" class="btn" data-toggle="tooltip" title='Delete' onclick="submitResult(event, this.form)" aria-hidden="true">&#128465;</button>
  1. 修改JS函数逻辑
    让函数接收表单参数,直接提交对应表单:
function submitResult(e, form) {
    e.preventDefault();
    Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire(
                'Deleted!',
                'Your file has been deleted.',
                'success'
            )
            form.submit(); // 直接提交当前按钮所属的表单
        }
    })
}

备选方案(唯一id方式)

如果坚持使用id定位表单,可为每个表单生成唯一id:

  1. 更新视图中的表单id
    用用户id作为表单id的后缀:
<form action="/cpanel/{{ $user->id }}" method="POST" id="EditForm-{{ $user->id }}">
  1. 更新按钮的onclick事件
    传递用户id给JS函数:
<button type="submit" class="btn" data-toggle="tooltip" title='Delete' onclick="submitResult(event, {{ $user->id }})" aria-hidden="true">&#128465;</button>
  1. 修改JS函数
    根据用户id拼接表单id并提交:
function submitResult(e, userId) {
    e.preventDefault();
    Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire(
                'Deleted!',
                'Your file has been deleted.',
                'success'
            )
            document.getElementById(`EditForm-${userId}`).submit();
        }
    })
}

额外优化建议

清理视图中重复的SweetAlert2引入(已通过CDN加载sweetalert2@11,无需再引入本地的sweetalert2.all.min.js),避免资源冲突。

内容的提问来源于stack exchange,提问作者nabil1997

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:05:53