简体   繁体   中英

Dynamically add input fields and save data to Database in lravel

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 Invalid argument supplied for foreach()

** error. Thanks in advanced.

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[]"...

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM