matlabmann 2018-08-24 10:15
浏览 580
已采纳

将多个数据保存到Laravel中的数据库中

I have a form within a table that has different fields. I want to be able to store all the data once. I hve search Stack overflows, all the answer i got did not solve the issue.Hence, I have to post my own question. The View

<td><input type="text" name="sflt[]" value="{{ $r['fltno'] }}" readonly="readonly" class="form-control"/></td>
<td><input type="text" name="smodel[]" value="{{ $r['model']}}" readonly="readonly" class="form-control"/></td> 
<td><input type="text" name="sengine[]" value="{{ $r['engine_type'] }}" readonly="readonly" class="form-control"/></td> 
<td><input type="text" name="sloc[]" value="{{ $r['location'] }}" readonly="readonly" class="form-control"/></td> 
<td><input type="text" name="sstye[]" value="{{ $sty }}" readonly="readonly" class="form-control"/></td> 
<td><input type="text" name="snsvr[]" value="{{ $nsvr}}" readonly="readonly" class="form-control"/></td> 

Controller

          $data = [];
          **//Get the input variables**
          $fltno= $request['sflt'];
          $model = $request['smodel'];
          $engine = $request['sengine'];
          $loc  = $request['sloc'];

// Store each varaibles as you fetch into the empty array

      foreach($fltno as $fltno)
         {
      $data[] = [
                'fltno'=>$request['sflt'],
                'model'=>$request['smodel'],
                'engine'=>$request['sengine'],
                loc'=>$request['sloc'],
               'serviceType'=>$request['sstye'],
               'nextSvr'=> $request['snsvr'] 
                ];
        }

       ModelName::insert($data); 

When I execute this, it throws error of: Invalid argument supplied for foreach()

Please, what am i doing wrong or what is the best way to insert all these data at once into the Database

  • 写回答

4条回答 默认 最新

  • dongzhen7108 2018-08-24 10:37
    关注

    Hi Dave I think you want to do something like this

    $data = $request->all();
    $finalArray = array();
    foreach($data as $key=>$value){
       array_push($finalArray, array(
                    'fltno'=>$value['sflt'],
                    'model'=>$value['smodel'],
                    'engine'=>$value['sengine'],
                    'loc'=>$value['sloc'],
                    'serviceType'=>$value['sstye'],
                    'nextSvr'=> $value['snsvr'] )
       );
    });
    
    Model::insert($finalArray);
    

    This will submit all data. I am assuming you are getting array in request with these keys.

    Hope this will help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里