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

Laravel:用Blade复制表单字段并通过Eloquent批量插入多行数据

Alright, let's build that "Add Another Form" functionality with batch Eloquent insertion. I'll walk you through each part step by step:

Step 1: Update Your Blade Template (create.blade.php)

First, we'll restructure your form to use array-named fields (so all repeated data gets bundled into a single array) and add a container for repeatable form groups, plus the "Add Another Form" button:

@extends('encoder-dashboard.layouts.app')

@section('css')
<link rel="stylesheet" href="/css/datepicker.css">
@endsection

@section('content')
<section class="content-header">
    <h1> Add New Analysis Request </h1>
</section>

<section class="content">
    <div class="box">
        <div class="box-body">
            <form action="{{ route('analysis-requests.store') }}" method="POST">
                @csrf
                <!-- Container for repeatable form field groups -->
                <div class="form-group-container">
                    <!-- Initial form group (index 0) -->
                    <div class="form-group-set" data-index="0">
                        <div class="form-group">
                            <label for="sample_name_0">Sample Name</label>
                            <input type="text" name="requests[0][sample_name]" id="sample_name_0" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label for="analysis_type_0">Analysis Type</label>
                            <select name="requests[0][analysis_type]" id="analysis_type_0" class="form-control" required>
                                <option value="type1">Type 1</option>
                                <option value="type2">Type 2</option>
                            </select>
                        </div>
                        <!-- Add all your other form fields here, following the same array naming pattern -->
                    </div>
                </div>

                <!-- "Add Another Form" Button -->
                <button type="button" id="add-form-btn" class="btn btn-primary mb-3">Add Another Form</button>

                <!-- Single Submit Button for All Forms -->
                <button type="submit" class="btn btn-success">Submit All Requests</button>
            </form>
        </div>
    </div>
</section>
@endsection

We're using requests[0][field_name] notation so all repeated form data is sent as a 2D array. The form-group-set class marks the block we'll duplicate, and we only keep one submit button for the entire form.

Step 2: Add JavaScript to Duplicate Form Fields

Add this script to your blade file (inside a @section('scripts') block) to handle copying form groups and updating field indices:

@section('scripts')
<script>
document.getElementById('add-form-btn').addEventListener('click', function() {
    const container = document.querySelector('.form-group-container');
    const lastFormSet = container.querySelector('.form-group-set:last-of-type');
    const currentIndex = parseInt(lastFormSet.getAttribute('data-index')) + 1;

    // Clone the last form group
    const newFormSet = lastFormSet.cloneNode(true);
    
    // Update all input/select names, IDs, and clear values
    newFormSet.querySelectorAll('input, select, textarea').forEach(element => {
        // Update name attribute with new index
        const oldName = element.getAttribute('name');
        element.setAttribute('name', oldName.replace(/\[(\d+)\]/, `[${currentIndex}]`));
        
        // Update ID attribute (for label association)
        const oldId = element.getAttribute('id');
        if (oldId) {
            element.setAttribute('id', oldId.replace(/(\d+)$/, currentIndex));
        }

        // Clear input values for the new form
        element.value = '';
    });

    // Update the index attribute for the new form set
    newFormSet.setAttribute('data-index', currentIndex);

    // Append the new form set to the container
    container.appendChild(newFormSet);
});
</script>
@endsection

This script copies the most recent form group, updates all field names/IDs to use the next index, clears input values, and adds the new group to the form.

Step 3: Handle Batch Insertion in Your Controller

In your AnalysisRequestController, use Eloquent's insert() method to save all rows in a single database query:

<?php

namespace App\Http\Controllers;

use App\Models\AnalysisRequest;
use Illuminate\Http\Request;

class AnalysisRequestController extends Controller
{
    public function store(Request $request)
    {
        // Validate all submitted form data
        $validatedData = $request->validate([
            'requests.*.sample_name' => 'required|string|max:255',
            'requests.*.analysis_type' => 'required|string|in:type1,type2',
            // Add validation rules for all your other fields here
        ]);

        // Insert all rows in one query using Eloquent
        AnalysisRequest::insert($validatedData['requests']);

        // Redirect back with success message
        return redirect()->route('analysis-requests.index')
            ->with('success', 'All analysis requests have been added successfully!');
    }
}

The insert() method accepts a 2D array and generates a single INSERT statement, which is far more efficient than saving each row individually.

Step 4: Configure Your Model

Make sure your AnalysisRequest model allows mass assignment for the fields you're submitting:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AnalysisRequest extends Model
{
    protected $fillable = [
        'sample_name',
        'analysis_type',
        // List all other fields you're including in the form here
    ];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:30:28