I have an issue in laravel with inserting data in multiple rows. I managed to insert the names in the ingredient table but I would like to add 2 other inputs (unit and quantity).
Can I do this without creating two more loops ?
Controller:
public function store() {
$meal = new Meal;
$meal->name = Input::get('name');
$ingredient_names = Input::get('ingredient_names');
$meal_ingredients = array();
foreach($ingredient_names as $ingredient_name)
{
$meal_ingredients[] = new Ingredient(array(
'name'=>$ingredient_name
));
}
//save into the DB
$meal->save();
$meal->ingredients()->saveMany($meal_ingredients);
}
create.blade.html:
<div class="panel-body">
{{ Form::open(array('route' => 'meals.store')) }}
<div class="form-group">
{{ Form::label('name', 'Name') }}
{{ Form::text('name', null, array('class' => 'form-control')) }}
</div>
<div class="input_fields_wrap">
<input class="form-control" type="text" name="ingredient_names[]">
<a class="add_field_button">Ajouter</a>
</div>
{{ Form::submit('Valider', array('class' => 'btn btn-primary')) }}
{!! Form::close() !!}
</div>
meal.js (just to show you that I am using dynamic fields)
// dynamic fields
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input class="form-control" type="text" name="ingredient_names[]"/><a href="#" class="remove_field">Supprimer</a></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})