我一直在尝试在我的数据表中上传 excel,但它不起作用。我正在上传成功消息数据,但它没有保存 excel 条目。
我也遵循了以下链接说明: https://www.studentstutorial.com/laravel/import https://www.webslesson.info/2019/02/import-excel-file-in-laravel.html
这是我的控制器:
//Save the File
if($request->hasFile('file'))
{
// Get the file with extension
$filenameWithExt = $request->file('file')->getClientOriginalName();
//Get the file name
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//Get the ext
$extension = $request->file('file')->getClientOriginalExtension();
//File name to store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload File
$path = $request->file('file')->storeAS('public/excels', $fileNameToStore);
}
$this->validate($request, [
'file' => 'required|mimes:xlsx,xls',
]);
$data = Excel::import(new Product, $path);
foreach ($data as $row) {
$arr[] = [
'Title' => $row->title,
'Text' => $row->text,
'Slug' => $row->slug,
'Brand_id' => $row->brand_id,
'Category_id' => $row->category_id,
'Image' => $row->image,
];
if (!empty($arr)) {
DB::table('products')->insert($arr);
}
}
return back()->with('success', 'Products Added');
我的表格:
<form role="form" method="POST" action="{{ action('ProductsController@import')}}" enctype="multipart/form-data">
@csrf
<div class="input-group mb-3 shadow">
<input type="file" name="file" class="btn btn-dark" title="Select File">
<button type="submit" class="btn btn-success rounded-0">Upload</button>
</div>
</form>
一段时间后,我能够自己解决它。我装箱了一个新的导入控制器,并在ProductsController@import中进行了此更改
我在控制器中所做的更改:
$products = Excel::toArray(new ProductsImport(), $request->file('file'));
foreach($products[0] as $row) {
// dd($row[1].' '.$row[2]);
$arr[] = [
// If uncomment this id from here, remove [0] from foreach
// 'id' => $row[0],
'image' => $row[1],
'title' => $row[2],
'slug' => $row[3],
'text' => $row[4],
'brand_id' => $row[5],
'category_id' => $row[6],
];
}
// dd($products);
if(!empty($arr)){
DB::table('products')->insert($arr);
}
return back()->with('success', 'Products Added');
现在,该文件正在保存在公共/excel中,并且数据正在导入到数据表中。