Reputation: 101
I'm trying to save dynamic inputs in multiple rows in my database.
This is a part of my form which are payments and dates.
<tr>
<td class="col-md-2">
{{Form::text('pay[]', '', ['class' => 'form-control number', 'placeholder' => ''])}}
</td>
<td class="col-md-2">
{{Form::text('payDate[]', '', ['class' => 'form-control pDate', 'placeholder' => ''])}}
</td>
<td class="col-md-2"><a class="deleteRow"></a>
</td>
</tr>
My JS code that add inputs dynamically:
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" id="field_2" class="form-control" name="pay[]" /></td>';
cols += '<td><input type="text" class="form-control pDate" name="payDate[]" /></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
And this is my Controller:
$input = $request->all();
for($i=0; $i<= count($input['pay']); $i++) {
$payment = new Payment;
$payment->file = $file;
$prePayment = str_replace(',', '', $request->input('pay'));
$payment->payment = $prePayment;
$payment->paymentDate = $request->input('payDate');
$payment->save();
}
Could you please help me to fix this issue.
At the moment I get this error:
Array to string conversion (SQL: insert into payments
(file
, payment
, paymentDate
, updated_at
, created_at
) values ....
Upvotes: 1
Views: 2275
Reputation: 9853
May be $request->input('pay')
this line causing the problem as you are trying to fetch whole array here, instead you should fetch single
object.
$input = $request->all();
$pays = $request->input('pay');
$paymentDates = $request->input('payDate');
for($i=0; $i< count($input['pay']); $i++) {
$payment = new Payment;
$payment->file = $file;
$prePayment = $pays[$i];
$payment->payment = str_replace(',','',$prePayment);
$payment->paymentDate = $paymentDates[$i];
$payment->save();
}
Upvotes: 1