简体   繁体   English

如何使用laravel将动态行的表数据保存到数据库中

[英]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. 我正在创建一个表,其中一行包含两个输入字段,如friend_name和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. 这是针对具有多个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. 但是我想一次创建多个朋友和那个朋友的多个联系人,并使用laravel将数据保存到数据库中,我该怎么做。

1) You need to post your Form by adding in your action attribute one link. 1)您需要通过在动作属性中添加一个链接来发布表单。 Also adding the csrf field. 还添加了csrf字段。 Because it protects your application from cross-site request forgery (CSRF) attacks. 因为它可以保护您的应用程序免受跨站点请求伪造(CSRF)攻击。 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. 2)您需要将此行添加到您的web.php文件中。 Note that the ControllerName must be your Actually Controller 请注意,ControllerName必须是您的实际控制器

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

3) Now in the Controller your have to insert your method. 3)现在,您必须在Controller中插入您的方法。 And that's it. 就是这样。

I hope it helps. 希望对您有所帮助。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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