【发布时间】:2020-05-27 23:16:54
【问题描述】:
我一直在尝试在我的数据表中上传 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>
【问题讨论】:
标签: php laravel maatwebsite-excel