Laravel insert multiple records in pivot table from arrays

786 views Asked by At

I'm trying to save multiple records(rows) in a table. The html fields are dynamic fields and declared as array, so they can be 1, 2 or more.

My blade:

<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">
<div class="input-group mb-3">
    <input type="text" name="tableName[]" class="form-control m-input" placeholder="Name"  autocomplete="off">
    <input type="text" name="fromNr[]" class="form-control m-input" placeholder="From"  autocomplete="off">
    <input type="text" name="toNr[]" class="form-control m-input" placeholder="to" autocomplete="off">
    <div class="input-group-append">                
        <button id="removeRow" type="button" class="btn btn-danger">X</button>
    </div>
</div>
+

My JS to create dynamic fields:

$("#addRow").click(function () {
    var html = '';
    html += '<div class="col-md-12" id="inputFormRow"  style="padding-left: 0px;">';
    html += '<div class="input-group mb-3">';
    html += '<input type="text" name="tableName[]"  class="form-control m-input" placeholder="Name" autocomplete="off">';
    html += '<input type="text" name="fromNr[]" class="form-control m-input" laceholder="From" autocomplete="off">';
     html += '<input type="text" name="toNr[]" class="form-control m-input" placeholder="To" autocomplete="off">';
    html += '<div class="input-group-append">';
    html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
    html += '</div>';
    html += '</div>';

    $('#newRow').append(html);
});

My Offer.php Model:

    protected $fillable = ['some columns];
    public function table()
    {
        return $this->hasMany(Table::class);
    }

My Table.php Model:

protected $fillable = ['offer_id','tableName','fromNr','toNr'];

public function offer()
{
    return $this->hasMany(Offer::class);
}

Now, in my Controller, I have to get request input values and then save into Table table. The input values can be more than 1 and dynamically.

My tries:

public function store(Request $request)
{   
    $statement = DB::select("SHOW TABLE STATUS LIKE 'offer'");
    $nextId = $statement[0]->Auto_increment;

    $tableName = $request->get('tableName');
    $fromNr = $request->get('fromNr');
    $toNr = $request->get('toNr');

    $offer = Offer::find($nextId);

    $offer->table()->saveMany([
        new Table(['restaurant_offer_id' => $nextId]),
        new Table(['tableName' => $tableName]),
        new Table(['fromNr' => $fromNr]),
        new Table(['toNr' => $toNr]),
        
    ]);
}

Thank you in Advance.

2

There are 2 answers

1
Fatur Rahman S On BEST ANSWER

If you want to make it dynamic you have to loop over the input array.

$tables = [];
foreach($tableName as $key => $value) {
    $table = new Table;
    $table->tableName = $tableName[$key];
    $table->fromNr = $fromNr[$key];
    $table->toNr = $toNr[$key];

    $tables[] = $table;
}

$offer->table()->saveMany($tables);
2
Mátyás Grőger On

If you use name="example[]" on the view, you are receiving the variable as an array in the controller. Also if you use Eloquent Model binding you can save the model instance to the database with simpler syntax.

Try something like this in the controller:

public function store(Request $request)
{   
    foreach($request->tableName as $key => $tableName)
    {
        Offer::create(['tableName' => $tableName',
                      'fromNr' => $request->fromNr[$key],
                      'toNr' => $request->toNr[$key]])
    }
   
}

Additionally I recommend to use plural naming in case of arrays. Like tableNames, fromNrs. So you know that it should contain multiple variables.