1

I use add/remove input fields with jquery and have problem when I want to update the values.

In the store() method foreach loop fetches all input fields that I added, while in the update() method foreach loop fetched only first input.

How can I fix this?

I have two tables "attributes(id,name)" and "attribute_option(id,attribute_id,attribute_value").

In edit.balde.php

<script type="text/javascript">
   $("#add").click(function(){
     addRow();
   }}

   function addRow(){
     $("optionsTable").append('<tr><td><input type="text" name="value[]" class="form-control"</td><td><button type="button" class="remove-tr">Remove</button></td></tr>);
   };

   $(document).on('click','.remove-tr', function(){
     $(this).parents('tr).remove();
   });
</script>

<button type="button" id="add">Add row</button>
@foreach($attribute_options as $key=>$option)
<tr>
   <td>
     <input type="hidden" name="option_id[]" value="{{ $option->id }}">
     <input type="text" name="value[]" value="{{ $option->attribute_value }}"> 
   </td>
   <td>
     <button type="button" class="remove-tr">Remove</button>
   </td>
</tr>
@endforeach

in my controller action update()

if($request->has('value)){
  $options = $request->value;
  $option_id = $request->option_id;
  foreach($options as $value){
     AttributeOption::where('id','=',$option_id)->update(array(
      'attribute_value' => $value
     ));
  }
}
2
  • In update(); what is the output dd($request->value) ? Commented Jul 13, 2020 at 7:33
  • value is type of array so i think you should assign options as $options = $request['value']; Commented Jul 13, 2020 at 7:35

1 Answer 1

1

Because $option_id is also an array and therefore also must be read as an array:

if($request->has('value')){
  $options = $request->value;
  $option_id = $request->option_id;
  foreach($options as $key => $value){
     AttributeOption::where('id','=',$option_id[$key])->update(array(
      'attribute_value' => $value
     ));
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.