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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大