下面是如何使用Excel将数据插入到学生表中的方法。当我使用excel插入数据时,它成功完成,但不幸的是,有些列显示为空,例如regiNo, firstName and lastName
。
我已经检查了数据库列名,它们是相同的。 Excel工作表标题名称也相同。
这怎么可能发生?
控制器
public function stdExcel(Request $request)
{
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
if(($request->file('imported-file')->getClientOriginalExtension()) != 'xlsx')
{
return redirect('/student/upload')->with('error','File Format may not be supported');
}
else {
$data = Excel::load($path, function($reader)
{})->get();
if(!($request->file('imported-file')->isValid()))
{
return redirect('/student/upload')->with('error','File upload failed');
}
else {
if(!empty($data) && $data->count())
{
foreach ($data->toArray() as $row)
{
if(!empty($row))
{
$dataArray[] =
[
'regiNo' => array_get($row, 'regiNo'),
'session' => array_get($row, 'session'),
'class' => array_get($row, 'class'),
'shift' => array_get($row, 'shift'),
'firstName' => array_get($row, 'firstName'),
'middleName' => array_get($row, 'middleName'),
'lastName' => array_get($row, 'lastName'),
'gender' => array_get($row, 'gender'),
'nationality' => array_get($row, 'nationality'),
'dob' => array_get($row, 'dob'),
'photo' => array_get($row, 'photo'),
'fatherCellNo' => array_get($row, 'fatherCellNo'),
];
}
}
if(!empty($dataArray))
{
Student::insert($dataArray);
return redirect('student/list')->with('status','Students successfully added');
}
}
}
}
}
else {
return redirect('/student/upload')->with('error','No file was uploaded. Please upload a file');
}
}
表格
Schema::create('Student', function(Blueprint $table)
{
$table->increments('id');
$table->string('regiNo',20);
$table->string('session',15)->nullable();
$table->string('class',100);
$table->string('shift',15)->nullable();
$table->string('firstName',60);
$table->string('middleName',60)->nullable();
$table->string('lastName',60);
$table->string('gender',10)->nullable();
$table->string('nationality',50)->nullable();
$table->string('dob',12)->nullable();
$table->string('photo',30)->nullable();
$table->string('fatherCellNo',15)->nullable();
$table->timestamps();
$table->index('regiNo');
});
答案 0 :(得分:0)
列是否始终为空?我的意思是所有记录中的regiNo
为空?
如果可以的话,我们可以看到您的迁移以及像shis这样的dd()
中的dataArray
:
if(!empty($row))
{
$dataArray[] =
[
'regiNo' => array_get($row, 'regiNo'),
'session' => array_get($row, 'session'),
'class' => array_get($row, 'class'),
'shift' => array_get($row, 'shift'),
'firstName' => array_get($row, 'firstName'),
'middleName' => array_get($row, 'middleName'),
'lastName' => array_get($row, 'lastName'),
'gender' => array_get($row, 'gender'),
'nationality' => array_get($row, 'nationality'),
'dob' => array_get($row, 'dob'),
'photo' => array_get($row, 'photo'),
'fatherCellNo' => array_get($row, 'fatherCellNo'),
];
dd($dataArray); // <<<<-------
}