Laravel 5.6&保存数组值

时间:2018-05-11 17:57:14

标签: php laravel-5

我对Laravel非常陌生,并试图创建简单的发票形式(到目前为止刚刚起草了几个字段)。发票的标题正确保存在db中,也是第一个InvoiceItem。但是,如果我在具有发票项目的表中添加多行,则只有第一个值保存在db中。

这是InvoiceItem行:

<tr>
<td>
<select class="form-control name" name="productname[]">
<option value="0" selected="true" disabled="true">Select Product</option>
@foreach($product_lists as $key=>$p)
<option value="{!!$key!!}">{!!$p!!}</option>
@endforeach                                             
</td>
<td><input type="text" class="form-control form-control-line qty" name="qty[]"></td>
<td><input type="text" class="form-control form-control-line price" name="price[]"></td>
<td><input type="text" class="form-control form-control-line total" name="total[]"></td>
<td><a href="#" class="remove">-<i class="glyphicon glyphicon-remove"></i></a></td>
</tr>

这是添加另一个InvoiceItem行的jquery:

function addRow(){
var tr='<tr>'+
'<td>'+
'<select class="form-control name" name="productname[]">'+
'<option value="0" selected="true" disabled="true">Select Product</option>'+
'@foreach($product_lists as $key=>$p)'+
'<option value="{!!$key!!}">{!!$p!!}</option>'+
'@endforeach'+                                      
'</td>'+
'<td><input type="text" class="form-control form-control-line qty" name="qty[]"></td>'+
'<td><input type="text" class="form-control form-control-line price" name="price[]"></td>'+
'<td><input type="text" class="form-control form-control-line total" name="total[]"></td>'+
'<td><a href="#" class="remove">-<i class="glyphicon glyphicon-remove"></i></a></td>'+
'</tr>';
$('tbody').append(tr);
};

这是我的控制者:

public function store(Request $request)
{
$salesinvoice = $this->validate(request(), [
'invoice_no' => 'required'
]);
SalesInvoice::create($salesinvoice);
foreach ($request->productname as $key=>$v) {
$data=array(
'product_id'=>$request->$v,
'qty'=>$request->qty[$key],
'price'=>$request->price[$key],
'total'=>$request->total[$key]
);
SalesInvoiceItem::insert($data);    
};

我很感激任何指导/提示如何解决它。

编辑:这是请求:

array:6 [▼
  "_token" => "xw1dkpYSjUNql1mHJLrreieRgcPk5nafpuvnawu0"
  "invoice_no" => "1000"
  "productname" => array:1 [▼
    0 => "1"
  ]
  "qty" => array:1 [▼
    0 => "5"
  ]
  "price" => array:1 [▼
    0 => "25"
  ]
  "total" => array:1 [▼
    0 => "125"
  ]
]

看起来问题出在表单本身,而不是控制器,对吗?

1 个答案:

答案 0 :(得分:0)

插入数据时应该是$v而不是$request->$v

替换以下内容:

'product_id' => $request->$v,

人:

'product_id' => $v