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

Laravel中destroy方法删除异常:误删首个ID数据求助

问题排查:删除数据时误删ID最小条目

我想根据ID删除指定数据,但点击目标数据的删除按钮时,并没有删除该数据,反而删除了ID最小的那条数据。以下是相关代码,请帮忙排查:


路由文件(web.php)

Route::resource('dashboard/posts', DashboardPostController::class)->names([
        'index' => 'post-dashboard',
        'show' => 'post-show',
        'create' => 'post-create',
        'edit' => 'post-edit',
        'destroy' => 'post-delete',
        'update' => 'post-edit'
    ]);

控制器(PostController.php)

public function destroy(Post $post)
{
    if ($post->image) {
        Storage::delete($post->image);
    }

    Post::destroy($post->id);

    $notif = [
        'message' => 'Data has been Deleted',
        'alert-type' => 'success'
    ];
    return redirect()->route('post-dashboard')->with($notif);
}

视图文件(post.blade.php)

<form action="{{ route('post-delete', $post->slug) }}" method="POST" class="d-inline" id="deleteForm">
    @csrf
    @method('DELETE')
    <button type="button" class="badge bg-danger border-0">
        <i class="material-icons opacity-10" onclick=" confirmDelete()">cancel</i>
    </button>
</form>

模型文件(Post.php)

public function getRouteKeyName()
{
    return 'slug';
}

public function sluggable(): array
{
    return [
        'slug' => [
            'source' => 'title'
        ]
    ];
}

问题根源

核心问题出在视图的表单和JS交互上:

  1. 页面中所有删除表单都使用了同一个id="deleteForm",ID是页面唯一标识,重复使用会导致JS只能定位到第一个匹配的表单(对应ID最小的条目)。
  2. 按钮是type="button",依赖confirmDelete()函数提交表单,但函数未针对目标表单做定位,只会提交第一个匹配的表单。

解决方案

1. 修复表单ID重复问题

给每个表单设置唯一ID,比如结合帖子ID:

<form action="{{ route('post-delete', $post->slug) }}" method="POST" class="d-inline" id="deleteForm-{{ $post->id }}">
    @csrf
    @method('DELETE')
    <button type="button" class="badge bg-danger border-0" onclick="confirmDelete({{ $post->id }})">
        <i class="material-icons opacity-10">cancel</i>
    </button>
</form>

2. 完善confirmDelete()函数

让函数根据传入的ID定位对应表单并提交:

function confirmDelete(postId) {
    if (confirm('确定要删除这条数据吗?')) {
        document.getElementById('deleteForm-' + postId).submit();
    }
}

3. 优化控制器destroy方法

既然已经通过路由模型绑定拿到了目标$post实例,直接调用delete()即可,无需再用静态方法destroy():

public function destroy(Post $post)
{
    if ($post->image) {
        Storage::delete($post->image);
    }

    $post->delete();

    $notif = [
        'message' => '数据已删除',
        'alert-type' => 'success'
    ];
    return redirect()->route('post-dashboard')->with($notif);
}

内容的提问来源于stack exchange,提问作者Muhammad farhan novian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 20:01:21