Reputation: 13
I have a file I am uploading and I am passing an partid along with it. I need to insert the records from the csv file into the table along with the partid in each record.
Inserting the records from the file works fine.
I need to add the partid to the array. I have not been able to figure out how. Any suggestions would be appreciated.
Submit Form
<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>
Controller
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();
}
Upvotes: 1
Views: 797
Reputation: 33427
Regarding Laravel doc: https://laravel.com/docs/5.6/requests
public function store(Request $request)
{
$partId = $request->input('part_id');
//
}
Then you pass your variable $partId
where ever you need it.
Upvotes: 1
Reputation: 35200
You should just be able to include it in the foreach loop:
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'],
]);
}
Or to make your code shorter you could do:
foreach ($rows as $row) {
$row = array_combine($header, $row);
$row['part_id'] = $request->part_id;
Bom::create($row);
}
Upvotes: 2