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 id="inputFormRow" style="padding-left: 0px;">
<div >
<input type="text" name="tableName[]" placeholder="Name" autocomplete="off">
<input type="text" name="fromNr[]" placeholder="From" autocomplete="off">
<input type="text" name="toNr[]" placeholder="to" autocomplete="off">
<div >
<button id="removeRow" type="button" >X</button>
</div>
</div>
My JS to create dynamic fields:
$("#addRow").click(function () {
var html = '';
html = '<div id="inputFormRow" style="padding-left: 0px;">';
html = '<div >';
html = '<input type="text" name="tableName[]" placeholder="Name" autocomplete="off">';
html = '<input type="text" name="fromNr[]" laceholder="From" autocomplete="off">';
html = '<input type="text" name="toNr[]" placeholder="To" autocomplete="off">';
html = '<div >';
html = '<button id="removeRow" type="button" >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.
CodePudding user response:
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);
CodePudding user response:
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.
