将变量插入Laravel CSV文件导入数组

时间:2018-06-20 14:57:15

标签: php arrays laravel csv

我有一个文件要上传,并且要传递一个partid。我需要将csv文件中的记录以及每个记录中的partid插入表中。

从文件插入记录工作正常。

我需要将partid添加到数组中。我还不知道怎么做。任何建议,将不胜感激。

提交表格

<form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 10px;"
      action="/part/importbom" class="form-horizontal" method="post"
      enctype="multipart/form-data">

    {{ csrf_field() }}
    <input type="file" name="file"/>
    <input type="hidden" name="part_id" value="{{ $part->id }}"/>
    <button class="btn btn-primary">Import File</button>
</form>

控制器

public function importExcel(Request $request)
{
    $partid = $request->part_id;

    $validator = \Validator::make($request->all(), [
        'file' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect()->back()->withErrors($validator);
    }

    $file = $request->file('file');
    $csvData = file_get_contents($file);

    $rows = array_map('str_getcsv', explode("\n", $csvData));
    $header = array_shift($rows);

    foreach ($rows as $row) {
        $row = array_combine($header, $row);
        // dd($row);
        Bom::create([
            'item'             => $row['item'],
            'qty'              => $row['qty'],
            'designators'      => $row['designators'],
            'hand_add'         => $row['hand_add'],
            'hand_solder'      => $row['hand_solder'],
            'hand_solder_pins' => $row['hand_solder_pins'],
            'notes'            => $row['notes'],
            'install'          => $row['install'],
        ]);
    }

    return redirect()->back();
}

2 个答案:

答案 0 :(得分:1)

关于Laravel文档:https://laravel.com/docs/5.6/requests

public function store(Request $request)
{
    $partId = $request->input('part_id');

    //
}

然后,将变量$partId传递到需要的地方。

答案 1 :(得分:1)

您应该可以将其包括在foreach循环中:

foreach ($rows as $row) {

    $row = array_combine($header, $row);

    Bom::create([
        'part_id'          => $request->part_id,
        'item'             => $row['item'],
        'qty'              => $row['qty'],
        'designators'      => $row['designators'],
        'hand_add'         => $row['hand_add'],
        'hand_solder'      => $row['hand_solder'],
        'hand_solder_pins' => $row['hand_solder_pins'],
        'notes'            => $row['notes'],
        'install'          => $row['install'],
    ]);
}

或者使代码更短,您可以这样做:

foreach ($rows as $row) {

    $row = array_combine($header, $row);

    $row['part_id'] = $request->part_id;

    Bom::create($row);
}