How to insert multiple rows in laravel 5?
laravel, laravel-5
Solution
You can use `insert()` method:
foreach ($rows as $row)
{
$charges[] = [
'course_id' => $request->input('Facture_id'),
'Title' => $row['Title'],
'Quantity' => $row['Quantity'],
'Price' => $row['Price'],
];
}
Charge::insert($charges);
Don't forget to add all column names you use to a `$fillable` array:
$fillable = ['course_id', 'Title', 'Quantity', 'Price'];
Problem
I want to insert an array with an id : create.blade : ``` {{ Form::open(array('route' => 'Charge.store','method'=>'POST')) }} <select id="disabledSelect" class="form-control" name="Facture_id"> <option value="{{ $Facture->id }}" >{{ $Facture->Num }}</option> </select> <br/> <div class="form-inline"> <div class="form-group"> <input type="text" class="form-control" name="rows[0][Title]" placeholder="libelé"/> </div> <div class="form-group"> <input type="text" class="form-control" name="rows[0][Quantity]" placeholder="Quantité"/> </div> <div class="form-group"> <input type="text" class="form-control" name="rows[0][Price]" placeholder="Prix unitaire "/> </div> <div class="form-group"> <input type="button" class="btn btn-default" value="Ajouter" onclick="createNew()" /> </div> <div id="mydiv"></div> </div> <br/> <div class="form-group"> <input type="submit" value="Ajouter" class="btn btn-info"> <a href="{{ route('Facture.index') }}" class="btn btn-default">Cancel</a> </div> {{ Form::close() }} <script> var i = 2; function createNew() { $("#mydiv").append('<div class="form-group">'+'<input type="text" name="rows[' + i +'][Title]" class="form-control" placeholder="libelé"/>'+ '</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Quantity]" class="form-control" placeholder="Quantité"/>'+'</div>'+'<div class="form-group">'+'<input type="text" name="rows[' + i +'][Price]" class="form-control" placeholder="Prix unitaire "/>'+'</div>'+'<div class="form-group">'+ '<input type="button" name="" class="btn btn-default" value="Ajouter" onclick="createNew()" />'+ '</div><br/>'); i++; } </script> ``` here is my controller , when I tried to submit the form , it inject rows with value of 0. What should I do ? I tried to use `elequent bolk` data , but the problem remain the same: ``` public function store(Request $request) { // validated input request $this->validate($request, [ 'Facture_id' => 'required', ]); // create new task $rows = $request->input('rows'); foreach ($rows as $row) { $Charges[] = new Charge(array( 'course_id'=>$request->input('Facture_id'), 'Title'=>$row['Title'], 'Quantity'=>$row['Quantity'], 'Price'=>$row['Price'], )); } Charge::create($Charges); return redirect()->route('Charge.index')->with('success', 'Your task added successfully!'); } ```