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

Laravel使用Ajax实现表格实时更新删除报错无法写入数据库

问题根因
  • 控制器更新逻辑存在语法错误:edit分支中先调用first()查询出单条用户记录对象,随后直接将$updaterole变量赋值为前端传入的role字符串,覆盖了原对象;后续调用$update->update()时$update变量未定义,直接触发500报错。
  • 前端未配置可编辑表格逻辑:当前Blade模板的Role列仅输出纯文本,没有绑定tabledit插件的编辑、请求发送逻辑,无法向后端提交编辑后的数据。
  • AJAX请求未携带CSRF令牌:直接在DOM中放置@csrf生成的隐藏域无法被tabledit的AJAX请求自动携带,会触发419 CSRF校验失败错误。
修复方案

1. 修正控制器更新逻辑

替换EventController中action方法的edit分支代码,移除错误的变量覆盖、未定义变量调用,直接通过查询构造器执行更新:

function action(Request $request)
{
    if($request->ajax())
    {
        if($request->action == 'edit')
        {
            DB::table('users')
                ->where('id', $request->id)
                ->update([
                    'role' => $request->role
                ]);
        }

        if($request->action == 'delete')
        {
            DB::table('users')
                ->where('id', $request->id)
                ->delete();
        }
        return response()->json(['code' => 0, 'msg' => 'success']);
    }
}

2. 补全前端可编辑表格配置

移除模板中无效的孤立@csrf标签,在表格渲染完成后初始化tabledit插件,配置可编辑列、提交地址,全局注入CSRF令牌:

<div class="table-responsive">
    <table id="editable" class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>First Name</th>
                <th>Email</th>
                <th>Role</th>
            </tr>
        </thead>
        <tbody>
            @foreach($allusers as $row)
            <tr>
                <td>{{ $row->id }}</td>
                <td>{{ $row->name }}</td>
                <td>{{ $row->email }}</td>
                <td>{{ $row->role }}</td>
            </tr>
            @endforeach
        </tbody>
    </table>
</div>

<!-- 请提前在页面引入jQuery、jquery-tabledit插件依赖 -->
<script>
$(function(){
    // 全局AJAX请求携带CSRF令牌,解决419报错
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        }
    });

    // 初始化可编辑表格
    $('#editable').Tabledit({
        url: '{{ route('tabledit.action') }}',
        dataType: 'json',
        columns: {
            identifier: [0, 'id'], // 指定第1列为ID主键
            editable: [
                [3, 'role'] // 指定第4列(Role列)为可编辑列,对应数据库字段role
            ]
        },
        deleteButton: true,
        saveButton: true,
        autoFocus: false
    });
})
</script>

3. 生效验证

修改完成后执行php artisan route:clear清除路由缓存,刷新浏览器缓存后重新访问页面,点击Role列单元格即可编辑内容,点击保存后数据会正常写入数据库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 02:51:32