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

Laravel删除记录异常:总是删除最后一条而非目标记录

问题分析与修复方案

核心问题

  • 所有删除按钮绑定同一个模态框,而模态框在循环外部引入,导致表单的action始终使用循环最后一条记录的ID,因此无论点击哪条记录的删除按钮,最终都会删除最后一条记录。
  • 路由定义存在语法错误(缺少逗号)。
  • 控制器中存在多余的DB::commit()(无事务场景下无需手动提交)。

1. 修复路由语法错误

修改routes/web.php中的路由,补上{record}与控制器之间的逗号:

Route::middleware('auth')->prefix('users')->name('users.')->group(function(){
    Route::delete('/deleterecord/{record}', [RecordsController::class, 'destroy'])->name('destroyrecord');
});

2. 修改视图删除按钮,传递记录ID

在循环内的删除按钮添加data-record-id属性,存储当前记录的ID:

<a class="btn-sm btn-danger m-2" href="#" data-toggle="modal" data-target="#deleteRecordModal" data-record-id="{{ $record->id }}">
    <i class="fas fa-trash"></i>
</a>

3. 改造模态框,动态更新表单提交地址

修改模态框中的表单,移除固定的action值,添加JavaScript动态设置提交地址:

<div class="modal fade" id="deleteRecordModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalExample"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalExample">Delete Customer</h5>
                <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">Are you sure you want to delete?</div>
            <div class="modal-footer">
                <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                <a class="btn btn-danger" href="#"
                    onclick="event.preventDefault(); document.getElementById('record-delete-form').submit();">
                    Delete
                </a>
                <form id="record-delete-form" method="POST" action="">
                    @csrf
                    @method('DELETE')
                </form>
            </div>
        </div>
    </div>
</div>

<script>
$('#deleteRecordModal').on('show.bs.modal', function (event) {
    const button = $(event.relatedTarget);
    const recordId = button.data('record-id');
    const form = $('#record-delete-form');
    // 拼接正确的删除路由地址
    const deleteUrl = "{{ route('users.destroyrecord', '') }}/" + recordId;
    form.attr('action', deleteUrl);
});
</script>

4. 优化控制器代码

移除多余的DB::commit()(无事务上下文时无需手动提交):

public function destroy(Records $record) {
    $record->delete();
    return redirect()->route('users.viewrecord')->with('success', 'Customer deleted successfully');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:36:07