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

Livewire中使用SweetAlert2做删除确认时误删所有帖子如何解决

问题根因

  • 列表页的删除按钮调用deleteConfirm方法时没有传递对应帖子的唯一ID,后端无法识别待删除的目标条目
  • 前端和后端的事件交互全程没有携带目标ID参数,确认删除时触发的delete事件是全局事件,后端delete方法直接操作$this->post,如果$this->post是整个列表的查询集合就会直接删除所有数据

修复代码

1. 调整post.list.blade按钮代码

在循环渲染帖子的逻辑中,给删除按钮传入当前帖子ID:

<!-- 假设你在@foreach($posts as $post)循环内渲染每个帖子的删除按钮 -->
<button wire:click="deleteConfirm({{ $post->id }})" type="button">delete</button>

2. 调整Livewire组件的deleteConfirm方法

接收帖子ID并随事件传递给前端:

public function deleteConfirm($postId)
{
    $this->emit('swal', 'are u sure?', 'warning', $postId);
}

3. 调整前端JS代码

接收ID并在确认删除时回传给后端:

const Swal = Swal.mixin({
    position: 'center',
    showConfirmButton: true,
})

document.addEventListener('livewire:load', () => {
    Livewire.on('swal', (message,type, postId) => {
        Swal.fire({
            icon: type,
            text: message,
            showCancelButton: true,
        }).then((result) => {
            if (result.isConfirmed) {
                Livewire.emit('delete', postId)
            }
        })
    })
})

4. 调整后端delete方法

根据传入ID查询对应帖子再执行删除,建议增加权限校验避免越权操作:

public function delete($postId)
{
    // 可在此处增加权限校验逻辑,例如判断当前登录用户是否拥有该帖子的删除权限
    $post = Post::findOrFail($postId);
    $post->delete();
    // 刷新帖子列表数据
    $this->posts = Post::where('user_id', auth()->id())->latest()->get();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 17:18:04