簡體   English   中英

如何使用laravel請求處理數組?

[英]How to handle array with laravel requests?

我正在使用這樣的簡單形式和數組輸入(不是動態的)

<input type="text" name="pre_ref_position[]" id="pre_ref_position">
<input type="text" name="pre_ref_position[]" id="pre_ref_position">

用ajax表單發布並返回這樣的數據;

[
    0:{pre_ref_position:'example1'}
    1:{pre_ref_position:'example2'}
]

因此,我想雄辯地保存此數據,但是如何處理該數組並將每一行保存在數據庫中呢?

假設您在控制器中名為$refVal的變量中接收到數組

然后使用以下代碼:

$refArr = [];
foreach($refVal as $key => $val)
{
  $now = Carbon::now();
  //ref_pos in the array below refers to the field name in your database.
  $refArr[] = [ 'ref_pos' => $val['pre_ref_position'] ,'created_at' => $now, 'updated_at' => $now ];
}


//assuming model name is `Position`
Position::insert($refArr);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM