matlabmann 2018-08-24 02: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 02: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部