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

Laravel 5.7:如何将动态添加的输入数据以单ID存入数据库单列

How to Save Dynamic Itinerary Inputs to a Single Database Column in Laravel 5.7

Hey there! Let's walk through how to capture those dynamic inputs and store them in a single database column. We'll cover front-end tweaks, back-end handling, and database setup step by step.

1. Fix the Front-End Input Names

First, your current input fields use name="[]" which is too vague. Let's give them a meaningful name like itineraries[] so Laravel can recognize them as an array. Update both the initial input and the ones added via JavaScript:

Updated View Code:

<div class="row">
    <div class="col-md-6">
        <div class="form-group row">
            <div class="col-sm-9" id="dynamic_field">
                <div class="input-group">
                    <input type="text" name="itineraries[]" class="form-control" placeholder="Enter itinerary"/>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="form-group row">
            <div class="col-sm-9">
                <button type="button" name="add" id="add" class="btn btn-gradient-primary">Add Itinerary</button>
            </div>
        </div>
    </div>
</div>

2. Update the JavaScript for Dynamic Inputs

Make sure the dynamically added inputs also use the itineraries[] name. Here's the corrected JS (I added small spacing classes for better UI—feel free to adjust based on your styling):

Updated JavaScript:

<script>
$(document).ready(function() {
    var i = 1;
    $('#add').click(function() {
        i++;
        $('#dynamic_field').append('<div id="row'+i+'" class="input-group mt-2"><input type="text" name="itineraries[]" class="form-control" placeholder="Enter itinerary"/><span class="input-group-btn ml-2"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></span></div>');
    });
    $(document).on('click', '.btn_remove', function(){
        var button_id = $(this).attr("id");
        $('#row'+button_id+'').remove();
    });
});
</script>

3. Handle the Input in Your Laravel Controller

Now, in your controller's store method, you'll receive the itineraries array. We recommend converting this array to a JSON string (it’s easier to parse and modify later) or a comma-separated string. Here's how:

Controller Code Example:

use Illuminate\Http\Request;

public function store(Request $request)
{
    // Optional but recommended: Validate the input
    $validated = $request->validate([
        'itineraries' => 'required|array',
        'itineraries.*' => 'required|string|max:255', // Ensure each entry is a valid string
    ]);

    // Convert the array to a JSON string (best practice for structured data)
    $itinerariesJson = json_encode($request->itineraries);

    // OR, if you prefer a comma-separated string:
    // $itinerariesString = implode(', ', $request->itineraries);

    // Save to your database (adjust the model and field name to match yours)
    $trip = new \App\Trip(); // Replace with your actual model
    $trip->itineraries = $itinerariesJson; // Use $itinerariesString if you chose that option
    $trip->save();

    return redirect()->back()->with('success', 'Itineraries saved successfully!');
}

4. Set Up the Database Column

Make sure your database table has a column that can store the JSON or string data. For JSON, use the json type (supported in MySQL 5.7+). For a comma-separated string, use text (to avoid length limits of varchar):

Migration Example:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTripsTable extends Migration
{
    public function up()
    {
        Schema::create('trips', function (Blueprint $table) {
            $table->increments('id');
            $table->json('itineraries'); // Use $table->text('itineraries'); if using comma-separated
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('trips');
    }
}

Bonus: Retrieving and Displaying the Data

If you stored the data as JSON, add an accessor to your model to automatically convert the JSON back to an array:

Model Accessor:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Trip extends Model
{
    // Automatically convert JSON to array when accessing the field
    public function getItinerariesAttribute($value)
    {
        return json_decode($value, true);
    }
}

Then in your view, you can loop through the itineraries easily:

@foreach($trip->itineraries as $itinerary)
    <p>{{ $itinerary }}</p>
@endforeach

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:16:53