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

Laravel中如何将多选复选框选中行数据插入数据库

问题:选中表格行插入SQL表时,未插入选中行而是默认前两行

我通过foreach从SQL获取了3行数据并展示在表格中,希望选中其中2行插入到另一张SQL表中。但当前编写的代码并未插入选中的行,而是默认插入了前两行,相关代码如下:

原前端代码

<table id="myTable" class="table table-hover">
    <thead>
    <tr>
        <th width="1%">#</th>
        <th width="10%">Name product</th>
        <th width="40%">Price<span class="text-danger font-weight-bold">*</span></th>
        <th width="6%">Status <span class="text-danger font-weight-bold">*</span></th>
        <th width="1%"></th>
    </tr>
    </thead>
    <tbody>
    @php($count = 0)
    @foreach($product as $row)
        @php($count++)
        <tr>
            <td><span>{{$count}}</span></td>
            <td><input type="text" name="product_name[]" value="{{ $row->product_name }}" class="form-control" readonly></td>
            <td><input type="number" name="product_rate[]" value="{{ $row->product_rate }}" class="form-control" readonly></td>
            <td><input type="text" name="product_status[]" value="{{ $row->product_status }}" class="form-control" readonly></td>
            <td><input type="checkbox" name="selectedRows[]" value="{{$count}}"></td>
        </tr>
    @endforeach
    </tbody>
</table>

原后端代码

public function newProductTable(Request $request)
{
    $selectedRows = $request->input('selectedRows', []);

    if (!$selectedRows) {
        return redirect()->back()->with('error', 'Error');
    } else {
        $current_date = date('Y-m-d H:i:s');
        {
            $selectedRows = $request->input('selectedRows', []);

            foreach ($selectedRows as $count) {
                DB::table('new_product_table')->insert([
                    'product_name' => $request->product_name[$count],
                    'product_rate' => $request->product_rate[$count],
                    'product_status' => $request->product_status[$count],
                    'created_at' => $current_date,
                    'updated_at' => $current_date,
                ]);
            }
        }

        return redirect()->back()->with('success', 'Successfully');
    }
}

问题原因

前端checkbox的value使用了自增的$count(从1开始),但后端接收的product_name[]、product_rate[]这类数组是从0开始索引的。比如选中第1行($count=1),后端取$request->product_name[1]实际对应表格中的第二行数据,索引错位导致插入了错误的行;如果选中第3行($count=3),甚至会因为数组越界取到空值,最终插入错误数据。

修正方案

1. 前端代码修改

将checkbox的value改为循环的0开始索引(用Laravel自带的$loop->index),或者直接使用数据库行的主键ID(更稳妥,避免分页/排序导致的索引混乱)。

基于索引的修改

<table id="myTable" class="table table-hover">
    <thead>
    <tr>
        <th width="1%">#</th>
        <th width="10%">Name product</th>
        <th width="40%">Price<span class="text-danger font-weight-bold">*</span></th>
        <th width="6%">Status <span class="text-danger font-weight-bold">*</span></th>
        <th width="1%"></th>
    </tr>
    </thead>
    <tbody>
    @php($count = 0)
    @foreach($product as $row)
        @php($count++)
        <tr>
            <td><span>{{$count}}</span></td>
            <td><input type="text" name="product_name[]" value="{{ $row->product_name }}" class="form-control" readonly></td>
            <td><input type="number" name="product_rate[]" value="{{ $row->product_rate }}" class="form-control" readonly></td>
            <td><input type="text" name="product_status[]" value="{{ $row->product_status }}" class="form-control" readonly></td>
            <!-- 使用$loop->index作为value,从0开始 -->
            <td><input type="checkbox" name="selectedRows[]" value="{{$loop->index}}"></td>
        </tr>
    @endforeach
    </tbody>
</table>

基于主键ID的修改(推荐)

<td><input type="checkbox" name="selectedRows[]" value="{{$row->id}}"></td>

2. 后端代码修改

对应前端索引修改的后端代码

去掉重复的$selectedRows赋值,增加索引有效性校验:

public function newProductTable(Request $request)
{
    $selectedRows = $request->input('selectedRows', []);

    if (empty($selectedRows)) {
        return redirect()->back()->with('error', '请选择要插入的行');
    }

    $current_date = date('Y-m-d H:i:s');
    
    foreach ($selectedRows as $index) {
        // 检查索引是否有效,避免数组越界
        if (!isset($request->product_name[$index])) {
            continue;
        }
        
        DB::table('new_product_table')->insert([
            'product_name' => $request->product_name[$index],
            'product_rate' => $request->product_rate[$index],
            'product_status' => $request->product_status[$index],
            'created_at' => $current_date,
            'updated_at' => $current_date,
        ]);
    }

    return redirect()->back()->with('success', '插入成功');
}

对应前端主键ID修改的后端代码(推荐)

通过ID查询原表数据后插入,避免索引错位风险:

public function newProductTable(Request $request)
{
    $selectedIds = $request->input('selectedRows', []);

    if (empty($selectedIds)) {
        return redirect()->back()->with('error', '请选择要插入的行');
    }

    $current_date = date('Y-m-d H:i:s');
    // 批量查询选中的产品数据,替换为实际产品表名
    $products = DB::table('原产品表名')->whereIn('id', $selectedIds)->get();
    
    foreach ($products as $product) {
        DB::table('new_product_table')->insert([
            'product_name' => $product->product_name,
            'product_rate' => $product->product_rate,
            'product_status' => $product->product_status,
            'created_at' => $current_date,
            'updated_at' => $current_date,
        ]);
    }

    return redirect()->back()->with('success', '插入成功');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 12:15:22