I am trying to upload number of students to a database via a csv file. I am able to upload a database to the csv file, however it is only uploading the first student to the database and not the rest. Any thoughts on what is going wrong?
Function which uploads the csv file to the database:
function csvstudents(Request $req) {
if ($req->hasFile('csvfile')) {
$path = $req->file('csvfile')->getRealPath();
$data = \Excel::load($path)->get();
if ($data->count()) {
foreach ($data as $key => $value) {
$arr = [
'studentID' => $value->studentID,
'name' => $value->name,
'var1' => $value->var1,
'var2' => $value->var2,
'email' => $value->email,
'address1' => $value->address1,
'c1' => $value->c1,
'c2' => $value->c2,
'c3' => $value->c3,
'c4' => $value->c4,
'c5' => $value->c5,
'c6' => $value->c6,
'c7' => $value->c7,
'c8' => $value->c8,
'c9' => $value->c9,
'c10' => $value->c10,
];
}
if (!empty($arr)) {
DB::table('students')->insert($arr);
return "Success";
}
}
}
}
Test CSV file:
9 Katy Perry A* WellDone! katy@hotmail.com 91 Fromans Road, Moseley, Birmingham, B94TJ 4 4 5 6 7 6 5 4 2 2
10 chut winder A* WellDone! katy@hotmail.com 92 Fromans Road, Moseley, Birmingham, B94TJ 4 4 5 6 7 6 5 4 2 2
11 Test A* WellDone! katy@hotmail.com 93 Fromans Road, Moseley, Birmingham, B94TJ 4 4 5 6 7 6 5 4 2 2
So f I was to upload the test database it would only insert the first student in to the database only, I want to upload all 3 entries.
You need to either insert inside the loop or push to $arr
and insert outside the loop
Inside loop
if ($data->count()) {
foreach ($data as $key => $value) {
$arr = ['studentID' => $value->studentID,
'name' => $value->name,
'var1' => $value->var1,
'var2' => $value->var2,
...
];
DB::table('students')->insert($arr);
}
return "Success";
}
Outside loop
if ($data->count()) {
$arr = [];
foreach ($data as $key => $value) {
$arr[] = ['studentID' => $value->studentID,
'name' => $value->name,
'var1' => $value->var1,
'var2' => $value->var2,
...
];
}
if (! empty($arr)) {
DB::table('students')->insert($arr);
return "Success";
}
}
You're not adding new values into $arr
, you're overwriting it on each iteration:
foreach ($data as $key => $value) {
$arr = ['studentID' => $value->studentID,
You probably want this:
$arr = [];
foreach ($data as $key => $value) {
$arr[] = ['studentID' => $value->studentID,
This assumes that your insert()
method can take an array. If that's not the case, then you can leave your array as is and just add a call to insert()
inside the loop.