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 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决