使用Laravel将动态生成的表单输入插入MySQL数据库

时间:2019-02-20 12:12:01

标签: php mysql laravel

我有一张向系统添加支票的表格。表格分为两部分:第一部分用于常见信息(即客户详细信息),第二部分用于唯一信息(即支票详细信息)。通过单击“添加”按钮可以为同一用户添加多个检查,该按钮会为表单生成重复的输入。 使用Laravel将数据保存在mysql数据库上时,出现错误

  

“未定义的偏移量:1”

这是我的laravel控制器:

public function store(Request $request)
{
  $customer_name = $request->customer_name;
  $cheque_number=$request->cheque_number;
  $count = count($cheque_number);

    for($i = 0; $i < $count; $i++){
        $objModel = new Cheque();
        $objModel->customer_name = $customer_name[$i];
        $objModel->cheque_number = $cheque_number[$i];
        $objModel->save();
    }
}

我的主要挑战是每个支票号码应保存在新行中,但要使用相同的客户名(仅提供一次)。

3 个答案:

答案 0 :(得分:1)

尝试这个

public function store(Request $request)
{
  $customer_name = $request->customer_name;
  $cheque_number = $request->cheque_number;
  $count = count($cheque_number);

    for($i = 0; $i < $count; $i++){
       if(isset($cheque_number[$i])) {  //for check value is set or not..
          $objModel = new Cheque();
          $objModel->customer_name = $customer_name;  //same name
          $objModel->cheque_number = $cheque_number[$i]; //different number
          $objModel->save();  
       }
    }
}

答案 1 :(得分:0)

public function store(Request $request){
 $customer_name = $request->get('customer_name');
 $cheque_number = $request->get('cheque_number');
 $count = count($cheque_number);

 for($i = 0; $i < $count; $i++){
  if(isset($cheque_number[$i])){
   $objModel = new Cheque();
          $objModel->customer_name = $customer_name;  //same name
          $objModel->cheque_number = $cheque_number[$i]; //different number
          $objModel->save(); 
  }
 }
}

答案 2 :(得分:-1)

您应该尝试以下操作:

public function store(Request $request)
{
  $customer_name = $request->customer_name;
  $cheque_number = $request->cheque_number;
  $count = count($cheque_number);

    for($i = 0; $i < $count; $i++){
       if(isset($cheque_number[$i])) {  
          $objModel = new Cheque();
          $objModel->customer_name = $customer_name;  //same name
          $objModel->cheque_number = $cheque_number[$i]; //different number
          $objModel->save();  
       }
    }
}