简体   繁体   中英

how to save table data of dynamic row into database using laravel

I am creating a table with one rows which contain two input fields as friend_name and Contact_no , and a buttons as "add contact" when user click on add contact then again a row create but with only one column as contact no. so user can add multiple contact for single friend and save it into database. this is done for one friend with multiple contact_no. at a time very easily. i am created for only one friend with multiple contact at a time as follow

 <form action "..." mehtod="post"> <table id="table1"> <thead> <tr> <th>friend</th> <th>Contact No.</th> </tr> </thead> <tbody> </table> <button id="addcontact" type="button" float: right;" onclick="addcontact()">add contact</button> <button id="deletecontact" type="button" float: right;" onclick="deletecontact()">delete contact</button> <input type="submit" value="submit" name="submit"> </form> <script> function addcontact() { document.getElementById("table1").insertRow(-1).innerHTML = '<td> <input type="hiddden"> </td><td> <input type="text" name="contact_no[]"></td>'; } function deletecontact() { var table = document.getElementById('table1'); var rowCount = table.rows.length; table.deleteRow(rowCount -1); } <script> 

and my controller is...

 public function addfriendcontact(Request $request) { $count = count(Input::get('contact_no')); for($i = 0; $i<$count; $i++) { $friend = new Friend; $friend->name = $request->name; $friend->contact_no = $request->contact_no[$i]; $friend->save(); } return back(); } 

but i want to create multiple friends and multiple contact of that friends at a time and save that data into database using laravel how can i do that.

1) You need to post your Form by adding in your action attribute one link. Also adding the csrf field. Because it protects your application from cross-site request forgery (CSRF) attacks. Without that, it will throw an error.

<form action="/contacts/insert-contact" mehtod="post"> 
{{ csrf_field() }}

2) You need to add this line to your web.php file. Note that the ControllerName must be your Actually Controller

Route::post('contacts/insert-contact','ControllerName@addfriendcontact');

3) Now in the Controller your have to insert your method. And that's it.

I hope it helps. :)

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