Reputation: 113
I want to save the multiple data to database with autoincremented id in the different column have a unique key for each data. User can dynamically add input fields and finally click submit button to save data in database with different id(auto incremented id) for each.
My js code id
<script>
$(document).ready(function(){
$('#add').click(function(){
var inp = $('#box');
var i = $('input').size() + 1;
$('<div id="box' + i +'"><input type="text" id="name" class="name" name="tagName' + i +'" placeholder="Input '+i+'"/><img src="<?php echo '../../uploads/remove.png'?>" width="32" height="32" border="0" align="top" class="add" id="remove" /> </div>').appendTo(inp);
i++;
});
$('body').on('click','#remove',function(){
$(this).parent('div').remove();
});
});
</script>
Form to insert data
<div class="row-fluid">
<div class="span6">
<div class="control-group">
<label class="control-label">Add Tags<span class="required"></span></label>
<div class="controls">
<div id="box">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="text" name="tagName[]" id="name" class="m-wrap span12" placeholder="Input Tags"
value="">
<a href="#" class="btn blue" id="add">Add More</a>
</div>
</div>
</div>
</div>
</div>
Controller function:
foreach( Input::get('tagName') as $name) {
$objectTagProduct = new TagModel;
$objectTagProduct ->name = $name;
$objectTagProduct->save();
}
I am able to insert only first data initially and now I am getting this error:
Invalid argument supplied for foreach()
Upvotes: 1
Views: 1584
Reputation: 8351
I think the problem is here:
$('<div id="box' + i +'"><input type="text" id="name" class="name" name="tagName' + i +'"...
^^^^^^^^^
You have to use brackets if you want to get tagName
as array:
$('<div id="box' + i +'"><input type="text" id="name" class="name" name="tagName[]"...
Upvotes: 1
Reputation: 21681
You can try to save below way.
$data[] = Input::get('tagName');
Print the $data and check record is arrive or not and then save below way.
foreach($data as $name) {
$objectTagProduct = new TagModel;
$objectTagProduct ->name = $name;
$objectTagProduct->save();
}
Upvotes: 0